code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
javascript DataView.prototype.getBigInt64() DataView.prototype.getBigInt64()
================================
The `getBigInt64()` method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getBigInt64(byteOffset)
getBigInt64(byteOffset, littleEndian)
```
### Parameters
byteOffset The offset, in bytes, from the start of the view to read the data from.
littleEndian Optional Indicates whether the 64-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 [`BigInt`](../bigint).
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such that 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 `getBigInt64` method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getBigInt64(0); // 0n
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getbigint64](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getbigint64) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getBigInt64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
* [`BigInt`](../bigint)
javascript DataView.prototype.setUint16() DataView.prototype.setUint16()
==============================
The `setUint16()` method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setUint16(byteOffset, value)
setUint16(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 setUint16 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setUint16(1, 3);
dataview.getUint16(1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setuint16](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setuint16) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUint16` | 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.getInt8() DataView.prototype.getInt8()
============================
The `getInt8()` method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getInt8(byteOffset)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to read the data.
### Return value
A signed 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 getInt8 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getInt8(1); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getint8](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getint8) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getInt8` | 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.setInt32() DataView.prototype.setInt32()
=============================
The `setInt32()` method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setInt32(byteOffset, value)
setInt32(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 setInt32 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setInt32(1, 3);
dataview.getInt32(1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setint32](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setint32) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setInt32` | 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.setBigInt64() DataView.prototype.setBigInt64()
================================
The `setBigInt64()` method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setBigInt64(byteOffset, value)
setBigInt64(byteOffset, value, littleEndian)
```
### Parameters
byteOffset The offset, in bytes, from the start of the view to store the data from.
value The value to set as a [`BigInt`](../bigint). The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`).
littleEndian Optional Indicates whether the 64-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 that it would store beyond the end of the view.
Examples
--------
### Using the `setBigInt64` method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setBigInt64(0, 3n);
dataview.getBigInt64(0); // 3n
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setbigint64](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setbigint64) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setBigInt64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
* [`BigInt`](../bigint)
javascript DataView.prototype.getBigUint64() DataView.prototype.getBigUint64()
=================================
The `getBigUint64()` method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getBigUint64(byteOffset)
getBigUint64(byteOffset, littleEndian)
```
### Parameters
byteOffset The offset, in bytes, from the start of the view to read the data from.
littleEndian Optional Indicates whether the 64-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 [`BigInt`](../bigint).
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such that 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 `getBigUint64` method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getBigUint64(0); // 0n
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getbiguint64](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getbiguint64) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getBigUint64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
* [`BigInt`](../bigint)
javascript DataView.prototype.setUint8() DataView.prototype.setUint8()
=============================
The `setUint8()` method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setUint8(byteOffset, value)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to store the data.
`value` The value to set.
### 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 setUint8 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setUint8(1, 3);
dataview.getUint8(1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setuint8](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setuint8) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUint8` | 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.getFloat32() DataView.prototype.getFloat32()
===============================
The `getFloat32()` method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getFloat32(byteOffset)
getFloat32(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 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 read.
### Return value
A signed 32-bit float 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 getFloat32 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getFloat32(1); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getfloat32](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getfloat32) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getFloat32` | 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.getInt16() DataView.prototype.getInt16()
=============================
The `getInt16()` method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getInt16(byteOffset)
getInt16(byteOffset, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to read the data.
`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 read.
### Return value
A signed 16-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 getInt16 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getInt16(1); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getint16](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getint16) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getInt16` | 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.getUint16() DataView.prototype.getUint16()
==============================
The `getUint16()` method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getUint16(byteOffset)
getUint16(byteOffset, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to read the data.
`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 read.
### Return value
An unsigned 16-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 getUint16 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getUint16(1); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getuint16](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getuint16) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUint16` | 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.buffer DataView.prototype.buffer
=========================
The `buffer` accessor property represents the [`ArrayBuffer`](../arraybuffer) or [`SharedArrayBuffer`](../sharedarraybuffer) referenced by the `DataView` 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 `DataView` is constructed and cannot be changed.
Examples
--------
### Using the buffer property
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.buffer; // ArrayBuffer { byteLength: 8 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-dataview.prototype.buffer](https://tc39.es/ecma262/multipage/structured-data.html#sec-get-dataview.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` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `sharedarraybuffer_support` | 60 | 79 | 79 | No | 47 | 10.1-11.1 | 60 | 60 | 79 | 44 | 10.3-11.3 | 8.0 | 1.0 | 8.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
* [`SharedArrayBuffer`](../sharedarraybuffer)
javascript DataView() constructor DataView() constructor
======================
The `DataView()` constructor is used to create [`DataView`](../dataview) objects.
Try it
------
Syntax
------
```
new DataView(buffer)
new DataView(buffer, byteOffset)
new DataView(buffer, byteOffset, byteLength)
```
**Note:** `DataView()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`buffer` An existing [`ArrayBuffer`](../arraybuffer) or [`SharedArrayBuffer`](../sharedarraybuffer) to use as the storage backing the new `DataView` object.
`byteOffset` Optional
The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte.
`byteLength` Optional
The number of elements in the byte array. If unspecified, the view's length will match the buffer's length.
### Return value
A new [`DataView`](../dataview) object representing the specified data buffer.
### Exceptions
[`RangeError`](../rangeerror) Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer.
For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer.
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-constructor](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview-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 |
| `DataView` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `new_required` | 11 | 13 | 40 | No | 15 | 5.1 | β€37 | 18 | 40 | 14 | 5 | 1.0 | 1.0 | 0.10.0 |
| `sharedarraybuffer_support` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [Polyfill of `DataView` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`DataView`](../dataview)
| programming_docs |
javascript DataView.prototype.setBigUint64() DataView.prototype.setBigUint64()
=================================
The `setBigUint64()` method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setBigUint64(byteOffset, value)
setBigUint64(byteOffset, value, littleEndian)
```
### Parameters
byteOffset The offset, in bytes, from the start of the view to store the data from.
value The value to set as a [`BigInt`](../bigint). The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`).
littleEndian Optional Indicates whether the 64-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 that it would store beyond the end of the view.
Examples
--------
### Using the setBigUint64() method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setBigUint64(0, 3n);
dataview.getBigUint64(0); // 3n
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setbiguint64](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setbiguint64) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setBigUint64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
* [`BigInt`](../bigint)
javascript DataView.prototype.setInt8() DataView.prototype.setInt8()
============================
The `setInt8()` method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setInt8(byteOffset, value)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to store the data.
`value` The value to set.
### 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 setInt8 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setInt8(1, 3);
dataview.getInt8(1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setint8](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setint8) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setInt8` | 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.getFloat64() DataView.prototype.getFloat64()
===============================
The `getFloat64()` method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getFloat64(byteOffset)
getFloat64(byteOffset, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to read the data.
`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 read.
### Return value
A signed 64-bit float 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 getFloat64 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getFloat64(0); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getfloat64](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getfloat64) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getFloat64` | 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 Uint8Array() constructor Uint8Array() constructor
========================
The `Uint8Array()` constructor creates a typed 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).
Syntax
------
```
new Uint8Array()
new Uint8Array(length)
new Uint8Array(typedArray)
new Uint8Array(object)
new Uint8Array(buffer)
new Uint8Array(buffer, byteOffset)
new Uint8Array(buffer, byteOffset, length)
```
**Note:** `Uint8Array()` 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 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 # 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 |
| `Uint8Array` | 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 `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 Float32Array() constructor Float32Array() constructor
==========================
The `Float32Array()` typed array constructor creates a new [`Float32Array`](../float32array) object, which is, 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).
Syntax
------
```
new Float32Array()
new Float32Array(length)
new Float32Array(typedArray)
new Float32Array(object)
new Float32Array(buffer)
new Float32Array(buffer, byteOffset)
new Float32Array(buffer, byteOffset, length)
```
**Note:** `Float32Array()` 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 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 # 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 |
| `Float32Array` | 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 `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.prototype.toLocaleDateString() Date.prototype.toLocaleDateString()
===================================
The `toLocaleDateString()` method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](../intl/datetimeformat) support, this method simply calls `Intl.DateTimeFormat`.
Try it
------
Syntax
------
```
toLocaleDateString()
toLocaleDateString(locales)
toLocaleDateString(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 that support the [`Intl.DateTimeFormat` API](../intl/datetimeformat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](../intl/datetimeformat/datetimeformat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](../intl/datetimeformat/datetimeformat#locales) parameter of the `Intl.DateTimeFormat()` constructor.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used.
`options` Optional
An object adjusting the output format. Corresponds to the [`options`](../intl/datetimeformat/datetimeformat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../typeerror) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored.
See the [`Intl.DateTimeFormat()` constructor](../intl/datetimeformat/datetimeformat) for details on these parameters and how to use them.
### Return value
A string representing the date portion of the given [`Date`](../date) instance according to language-specific conventions.
In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above.
Performance
-----------
When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](../intl/datetimeformat) object and use its [`format()`](../intl/datetimeformat/format) method.
Examples
--------
### Using toLocaleDateString()
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleDateString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleDateString());
// "12/11/2012" if run in en-US locale with time zone America/Los\_Angeles
```
### Checking for support for locales and options arguments
The `locales` and `options` arguments are not supported in all browsers yet. To check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a [`RangeError`](../rangeerror) exception:
```
function toLocaleDateStringSupportsLocales() {
try {
new Date().toLocaleDateString("i");
} catch (e) {
return e.name === "RangeError";
}
return false;
}
```
### Using locales
This example shows some of the variations in localized date formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// formats below assume the local time zone of the locale;
// America/Los\_Angeles for the US
// US English uses month-day-year order
console.log(date.toLocaleDateString("en-US"));
// "12/20/2012"
// British English uses day-month-year order
console.log(date.toLocaleDateString("en-GB"));
// "20/12/2012"
// Korean uses year-month-day order
console.log(date.toLocaleDateString("ko-KR"));
// "2012. 12. 20."
// Event for Persian, It's hard to manually convert date to Solar Hijri
console.log(date.toLocaleDateString("fa-IR"));
// "Ϋ±Ϋ³ΫΉΫ±/ΫΉ/Ϋ³Ϋ°"
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleDateString("ar-EG"));
// "Ω’Ω β/Ω‘Ω’β/Ω’Ω Ω‘Ω’"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleDateString("ja-JP-u-ca-japanese"));
// "24/12/20"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleDateString(["ban", "id"]));
// "20/12/2012"
```
### Using options
The results provided by `toLocaleDateString()` can be customized using the `options` argument:
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(date.toLocaleDateString("de-DE", options));
// "Donnerstag, 20. Dezember 2012"
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(date.toLocaleDateString("en-US", options));
// "Thursday, December 20, 2012, UTC"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.tolocaledatestring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.tolocaledatestring) |
| [ECMAScript Internationalization API Specification # sup-date.prototype.tolocaledatestring](https://tc39.es/ecma402/#sup-date.prototype.tolocaledatestring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLocaleDateString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `iana_time_zone_names` | 24 | 14 | 52 | No | 15 | 7 | 4.4 | 25 | 56 | 14 | 7 | 1.5 | 1.8 | 0.12.0 |
| `locales` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 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` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.0 | 0.12.0 |
See also
--------
* [`Intl.DateTimeFormat`](../intl/datetimeformat)
* [`Date.prototype.toLocaleString()`](tolocalestring)
* [`Date.prototype.toLocaleTimeString()`](tolocaletimestring)
* [`Date.prototype.toString()`](tostring)
javascript Date.prototype.getUTCMonth() Date.prototype.getUTCMonth()
============================
The `getUTCMonth()` returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year).
Try it
------
Syntax
------
```
getUTCMonth()
```
### Return value
A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Examples
--------
### Using getUTCMonth()
The following example assigns the month portion of the current date to the variable `month`.
```
const today = new Date();
const month = today.getUTCMonth();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutcmonth](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutcmonth) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCMonth` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getMonth()`](getmonth)
* [`Date.prototype.setUTCMonth()`](setutcmonth)
| programming_docs |
javascript Date.prototype.toLocaleString() Date.prototype.toLocaleString()
===============================
The `toLocaleString()` method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](../intl/datetimeformat) support, this method simply calls `Intl.DateTimeFormat`.
Try it
------
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 that support the [`Intl.DateTimeFormat` API](../intl/datetimeformat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](../intl/datetimeformat/datetimeformat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](../intl/datetimeformat/datetimeformat#locales) parameter of the `Intl.DateTimeFormat()` constructor.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used.
`options` Optional
An object adjusting the output format. Corresponds to the [`options`](../intl/datetimeformat/datetimeformat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored.
See the [`Intl.DateTimeFormat()` constructor](../intl/datetimeformat/datetimeformat) for details on these parameters and how to use them.
### Return value
A string representing the given date according to language-specific conventions.
In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`.
**Note:** Most of the time, the formatting returned by `toLocaleString()` is consistent. However, the output may vary with time, language, and implementation β output variations are by design and allowed by the specification. You should not compare the results of `toLocaleString()` to static values.
Examples
--------
### Using toLocaleString()
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleString() without arguments depends on the
// implementation, the default locale, and the default time zone
console.log(date.toLocaleString());
// "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los\_Angeles
```
### Checking for support for locales and options arguments
The `locales` and `options` arguments are not supported in all browsers yet. To check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a [`RangeError`](../rangeerror) exception:
```
function toLocaleStringSupportsLocales() {
try {
new Date().toLocaleString("i");
} catch (e) {
return e.name === "RangeError";
}
return false;
}
```
### 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));
// Formats below assume the local time zone of the locale;
// America/Los\_Angeles for the US
// US English uses month-day-year order and 12-hour time with AM/PM
console.log(date.toLocaleString("en-US"));
// "12/19/2012, 7:00:00 PM"
// British English uses day-month-year order and 24-hour time without AM/PM
console.log(date.toLocaleString("en-GB"));
// "20/12/2012 03:00:00"
// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(date.toLocaleString("ko-KR"));
// "2012. 12. 20. μ€ν 12:00:00"
// Arabic in most Arabic-speaking countries uses Eastern Arabic numerals
console.log(date.toLocaleString("ar-EG"));
// "Ω’Ω β/Ω‘Ω’β/Ω’Ω Ω‘Ω’ Ω₯:Ω Ω :Ω Ω Ψ΅"
// For Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleString("ja-JP-u-ca-japanese"));
// "24/12/20 12:00:00"
// When requesting a language that may not be supported, such as
// Balinese, include a fallback language (in this case, Indonesian)
console.log(date.toLocaleString(["ban", "id"]));
// "20/12/2012 11.00.00"
```
### Using options
The results provided by `toLocaleString()` can be customized using the `options` argument:
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Request a weekday along with a long date
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(date.toLocaleString("de-DE", options));
// "Donnerstag, 20. Dezember 2012"
// An application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(date.toLocaleString("en-US", options));
// "Thursday, December 20, 2012, GMT"
// Sometimes even the US needs 24-hour time
console.log(date.toLocaleString("en-US", { hour12: false }));
// "12/19/2012, 19:00:00"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.tolocalestring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.tolocalestring) |
| [ECMAScript Internationalization API Specification # sup-date.prototype.tolocalestring](https://tc39.es/ecma402/#sup-date.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 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `iana_time_zone_names` | 24 | 14 | 52 | No | 15 | 7 | 4.4 | 25 | 56 | 14 | 7 | 1.5 | 1.8 | 0.12.0 |
| `locales` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 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` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.0 | 0.12.0 |
See also
--------
* [`Intl.DateTimeFormat`](../intl/datetimeformat)
* [`Date.prototype.toLocaleDateString()`](tolocaledatestring)
* [`Date.prototype.toLocaleTimeString()`](tolocaletimestring)
* [`Date.prototype.toString()`](tostring)
javascript Date.prototype.getTime() Date.prototype.getTime()
========================
The `getTime()` method returns the number of milliseconds since the [epoch](../date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC.
You can use this method to help assign a date and time to another [`Date`](../date) object. This method is functionally equivalent to the [`valueOf()`](valueof) method.
Try it
------
Syntax
------
```
getTime()
```
### Return value
A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date.
Description
-----------
To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 20Β΅s in Firefox 59; in 60 it will be 2ms.
```
// reduced time precision (2ms) in Firefox 60
new Date().getTime();
// 1519211809934
// 1519211810362
// 1519211811670
// β¦
// reduced time precision with `privacy.resistFingerprinting` enabled
new Date().getTime();
// 1519129853500
// 1519129858900
// 1519129864400
// β¦
```
In Firefox, you can also enable `privacy.resistFingerprinting`, the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger.
Examples
--------
### Using `getTime()` for copying dates
Constructing a date object with the identical time value.
```
// Since month is zero based, birthday will be January 10, 1995
const birthday = new Date(1994, 12, 10);
const copy = new Date();
copy.setTime(birthday.getTime());
```
### Measuring execution time
Subtracting two subsequent `getTime()` calls on newly generated [`Date`](../date) objects, give the time span between these two calls. This can be used to calculate the executing time of some operations. See also [`Date.now()`](now) to prevent instantiating unnecessary [`Date`](../date) objects.
```
let end, start;
start = new Date();
for (let i = 0; i < 1000; i++) {
Math.sqrt(i);
}
end = new Date();
console.log(`Operation took ${end.getTime() - start.getTime()} msec`);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.gettime](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.gettime) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getTime` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.setTime()`](settime)
* [`Date.prototype.valueOf()`](valueof)
* [`Date.now()`](now)
javascript Date.prototype.toLocaleTimeString() Date.prototype.toLocaleTimeString()
===================================
The `toLocaleTimeString()` method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](../intl/datetimeformat) support, this method simply calls `Intl.DateTimeFormat`.
Try it
------
Syntax
------
```
toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(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 that support the [`Intl.DateTimeFormat` API](../intl/datetimeformat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](../intl/datetimeformat/datetimeformat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](../intl/datetimeformat/datetimeformat#locales) parameter of the `Intl.DateTimeFormat()` constructor.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used.
`options` Optional
An object adjusting the output format. Corresponds to the [`options`](../intl/datetimeformat/datetimeformat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored.
See the [`Intl.DateTimeFormat()` constructor](../intl/datetimeformat/datetimeformat) for details on these parameters and how to use them.
### Return value
A string representing the time portion of the given [`Date`](../date) instance according to language-specific conventions.
In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above.
Performance
-----------
When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](../intl/datetimeformat) object and use its [`format()`](../intl/datetimeformat/format) method.
Examples
--------
### Using toLocaleTimeString()
Basic use of this method without specifying a `locale` returns a formatted string in the default locale and with default options.
```
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleTimeString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleTimeString());
// "7:00:00 PM" if run in en-US locale with time zone America/Los\_Angeles
```
### Using locales
This example shows some of the variations in localized time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// formats below assume the local time zone of the locale;
// America/Los\_Angeles for the US
// US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("en-US"));
// "7:00:00 PM"
// British English uses 24-hour time without AM/PM
console.log(date.toLocaleTimeString("en-GB"));
// "03:00:00"
// Korean uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("ko-KR"));
// "μ€ν 12:00:00"
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleTimeString("ar-EG"));
// "Ω§:Ω Ω :Ω Ω Ω
"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleTimeString(["ban", "id"]));
// "11.00.00"
```
### Using options
The results provided by `toLocaleTimeString()` can be customized using the `options` argument:
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// an application may want to use UTC and make that visible
const options = { timeZone: "UTC", timeZoneName: "short" };
console.log(date.toLocaleTimeString("en-US", options));
// "3:00:00 AM GMT"
// sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString("en-US", { hour12: false }));
// "19:00:00"
// show only hours and minutes, use options with the default locale - use an empty array
console.log(
date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
);
// "20:01"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.tolocaletimestring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.tolocaletimestring) |
| [ECMAScript Internationalization API Specification # sup-date.prototype.tolocaletimestring](https://tc39.es/ecma402/#sup-date.prototype.tolocaletimestring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLocaleTimeString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `iana_time_zone_names` | 24 | 14 | 52 | No | 15 | 7 | 4.4 | 25 | 56 | 14 | 7 | 1.5 | 1.8 | 0.12.0 |
| `locales` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 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` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.0 | 0.12.0 |
See also
--------
* [`Intl.DateTimeFormat`](../intl/datetimeformat)
* [`Date.prototype.toLocaleDateString()`](tolocaledatestring)
* [`Date.prototype.toLocaleString()`](tolocalestring)
* [`Date.prototype.toTimeString()`](totimestring)
* [`Date.prototype.toString()`](tostring)
javascript Date.prototype[@@toPrimitive] Date.prototype[@@toPrimitive]
=============================
The `[@@toPrimitive]()` method converts a `Date` object to a primitive value.
Try it
------
Syntax
------
```
Date()[Symbol.toPrimitive](hint)
```
### Return value
The primitive value of the given [`Date`](../date) object. Depending on the argument, the method can return either a string or a number.
Description
-----------
The `[@@toPrimitive]()` method of the [`Date`](../date) object returns a primitive value, that is either of type number or of type string.
If `hint` is `string` or `default`, `[@@toPrimitive]()` tries to call the [`toString`](../object/tostring) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../object/valueof) method and if the `valueOf` does not exist either, `[@@toPrimitive]()` throws a [`TypeError`](../typeerror).
If `hint` is `number`, `[@@toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`.
JavaScript calls the `[@@toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[@@toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
Examples
--------
### Returning date primitives
```
const testDate = new Date(1590757517834);
// "Date Fri May 29 2020 14:05:17 GMT+0100 (British Summer Time)"
testDate[Symbol.toPrimitive]("string");
// Returns "Date Fri May 29 2020 14:05:17 GMT+0100 (British Summer Time)"
testDate[Symbol.toPrimitive]("number");
// Returns "1590757517834"
testDate[Symbol.toPrimitive]("default");
// Returns "Date Fri May 29 2020 14:05:17 GMT+0100 (British Summer Time)"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype-@@toprimitive](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype-@@toprimitive) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 |
See also
--------
* [`Symbol.toPrimitive`](../symbol/toprimitive)
javascript Date.now() Date.now()
==========
The `Date.now()` static method returns the number of milliseconds elapsed since the [epoch](../date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC.
Try it
------
Syntax
------
```
Date.now()
```
### Return value
A number representing the number of milliseconds elapsed since the [epoch](../date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC.
Examples
--------
### Reduced time precision
To offer protection against timing attacks and fingerprinting, the precision of `Date.now()` might get rounded depending on browser settings. In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 20Β΅s in Firefox 59; in 60 it will be 2ms.
```
// reduced time precision (2ms) in Firefox 60
Date.now();
// 1519211809934
// 1519211810362
// 1519211811670
// β¦
// reduced time precision with `privacy.resistFingerprinting` enabled
Date.now();
// 1519129853500
// 1519129858900
// 1519129864400
// β¦
```
In Firefox, you can also enable `privacy.resistFingerprinting`, the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.now](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.now) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `now` | 1 | 12 | 1 | 9 | 10.5 | 4 | 4.4 | 18 | 4 | 14 | 4 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Date.now` in `core-js`](https://github.com/zloirock/core-js#ecmascript-date)
* [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) β provides timestamps with sub-millisecond resolution for use in measuring web page performance
* [`console.time()`](https://developer.mozilla.org/en-US/docs/Web/API/console/time) / [`console.timeEnd()`](https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd)
| programming_docs |
javascript Date.prototype.setMonth() Date.prototype.setMonth()
=========================
The `setMonth()` method sets the month for a specified date according to the currently set year.
Try it
------
Syntax
------
```
setMonth(monthValue)
setMonth(monthValue, dayValue)
```
### Parameters
`monthValue` A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year.
`dayValue` Optional. An integer from 1 to 31, representing the day of the month.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `dayValue` parameter, the value returned from the [`getDate()`](getdate) method is used.
If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month.
The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.
Examples
--------
### Using setMonth()
```
const theBigDay = new Date();
theBigDay.setMonth(6);
//Watch out for end of month transitions
const endOfMonth = new Date(2016, 7, 31);
endOfMonth.setMonth(1);
console.log(endOfMonth); //Wed Mar 02 2016 00:00:00
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setmonth](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setmonth) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setMonth` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getMonth()`](getmonth)
* [`Date.prototype.setUTCMonth()`](setutcmonth)
javascript Date.prototype.getDay() Date.prototype.getDay()
=======================
The `getDay()` method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](getdate).
Try it
------
Syntax
------
```
getDay()
```
### Return value
An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
Examples
--------
### Using getDay()
The second statement below assigns the value 1 to `weekday`, based on the value of the [`Date`](../date) object `xmas95`. December 25, 1995, is a Monday.
```
const xmas95 = new Date("December 25, 1995 23:15:30");
const weekday = xmas95.getDay();
console.log(weekday); // 1
```
**Note:** If needed, the full name of a day (`"Monday"` for example) can be obtained by using [`Intl.DateTimeFormat`](../intl/datetimeformat) with an `options` parameter. Using this method, the internationalization is made easier:
```
const options = { weekday: "long" };
console.log(new Intl.DateTimeFormat("en-US", options).format(Xmas95));
// Monday
console.log(new Intl.DateTimeFormat("de-DE", options).format(Xmas95));
// Montag
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getday](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getday) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getDay` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCDate()`](getutcdate)
* [`Date.prototype.getUTCDay()`](getutcday)
* [`Date.prototype.setDate()`](setdate)
javascript Date.prototype.setTime() Date.prototype.setTime()
========================
The `setTime()` method sets the [`Date`](../date) object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
Try it
------
Syntax
------
```
setTime(timeValue)
```
### Parameters
`timeValue` An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument).
Description
-----------
Use the `setTime()` method to help assign a date and time to another [`Date`](../date) object.
Examples
--------
### Using setTime()
```
const theBigDay = new Date("July 1, 1999");
const sameAsBigDay = new Date();
sameAsBigDay.setTime(theBigDay.getTime());
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.settime](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.settime) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setTime` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getTime()`](gettime)
* [`Date.prototype.setUTCHours()`](setutchours)
javascript Date.prototype.setUTCFullYear() Date.prototype.setUTCFullYear()
===============================
The `setUTCFullYear()` method sets the full year for a specified date according to universal time.
Try it
------
Syntax
------
```
setUTCFullYear(yearValue)
setUTCFullYear(yearValue, monthValue)
setUTCFullYear(yearValue, monthValue, dayValue)
```
### Parameters
`yearValue` An integer specifying the numeric value of the year, for example, 1995.
`monthValue` Optional. An integer between 0 and 11 representing the months January through December.
`dayValue` Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`getUTCMonth()`](getutcmonth) and [`getUTCDate()`](getutcdate) methods are used.
If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the [`Date`](../date) object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month.
Examples
--------
### Using setUTCFullYear()
```
const theBigDay = new Date();
theBigDay.setUTCFullYear(1997);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setutcfullyear](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setutcfullyear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUTCFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCFullYear()`](getutcfullyear)
* [`Date.prototype.setFullYear()`](setfullyear)
javascript Date.prototype.getMilliseconds() Date.prototype.getMilliseconds()
================================
The `getMilliseconds()` method returns the milliseconds in the specified date according to local time.
Try it
------
Syntax
------
```
getMilliseconds()
```
### Return value
A number, between 0 and 999, representing the milliseconds for the given date according to local time.
Examples
--------
### Using getMilliseconds()
The following example assigns the milliseconds portion of the current time to the variable `milliseconds`:
```
const today = new Date();
const milliseconds = today.getMilliseconds();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getmilliseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getmilliseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCMilliseconds()`](getutcmilliseconds)
* [`Date.prototype.setMilliseconds()`](setmilliseconds)
javascript Date.prototype.getUTCSeconds() Date.prototype.getUTCSeconds()
==============================
The `getUTCSeconds()` method returns the seconds in the specified date according to universal time.
Try it
------
Syntax
------
```
getUTCSeconds()
```
### Return value
A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Examples
--------
### Using getUTCSeconds()
The following example assigns the seconds portion of the current time to the variable `seconds`.
```
const today = new Date();
const seconds = today.getUTCSeconds();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutcseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutcseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCSeconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getSeconds()`](getseconds)
* [`Date.prototype.setUTCSeconds()`](setutcseconds)
javascript Date.prototype.setUTCSeconds() Date.prototype.setUTCSeconds()
==============================
The `setUTCSeconds()` method sets the seconds for a specified date according to universal time.
Try it
------
Syntax
------
```
setUTCSeconds(secondsValue)
setUTCSeconds(secondsValue, msValue)
```
### Parameters
`secondsValue` An integer between 0 and 59, representing the seconds.
`msValue` Optional. A number between 0 and 999, representing the milliseconds.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `msValue` parameter, the value returned from the [`getUTCMilliseconds()`](getutcmilliseconds) method is used.
If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the [`Date`](../date) object will be incremented by 1, and 40 will be used for seconds.
Examples
--------
### Using setUTCSeconds()
```
const theBigDay = new Date();
theBigDay.setUTCSeconds(20);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setutcseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setutcseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUTCSeconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCSeconds()`](getutcseconds)
* [`Date.prototype.setSeconds()`](setseconds)
javascript Date.prototype.setMinutes() Date.prototype.setMinutes()
===========================
The `setMinutes()` method sets the minutes for a specified date according to local time.
Try it
------
Syntax
------
```
setMinutes(minutesValue)
setMinutes(minutesValue, secondsValue)
setMinutes(minutesValue, secondsValue, msValue)
```
### Parameters
`minutesValue` An integer between 0 and 59, representing the minutes.
`secondsValue` Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`.
`msValue` Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`getSeconds()`](getseconds) and [`getMilliseconds()`](getmilliseconds) methods are used.
If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds.
Examples
--------
### Using setMinutes()
```
const theBigDay = new Date();
theBigDay.setMinutes(45);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setminutes](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setminutes) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setMinutes` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getMinutes()`](getminutes)
* [`Date.prototype.setUTCMinutes()`](setutcminutes)
javascript Date.prototype.valueOf() Date.prototype.valueOf()
========================
The `valueOf()` method returns the primitive value of a [`Date`](../date) object.
Try it
------
Syntax
------
```
valueOf()
```
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../nan) in case of an invalid date.
Description
-----------
The `valueOf()` method returns the primitive value of a [`Date`](../date) object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC.
This method is functionally equivalent to the [`Date.prototype.getTime()`](gettime) method.
This method is usually called internally by JavaScript and not explicitly in code.
Examples
--------
### Using valueOf()
```
const x = new Date(56, 6, 17);
const myVar = x.valueOf(); // assigns -424713600000 to myVar
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.valueof](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.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` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.prototype.valueOf()`](../object/valueof)
* [`Date.prototype.getTime()`](gettime)
javascript Date.prototype.getSeconds() Date.prototype.getSeconds()
===========================
The `getSeconds()` method returns the seconds in the specified date according to local time.
Try it
------
Syntax
------
```
getSeconds()
```
### Return value
An integer number, between 0 and 59, representing the seconds in the given date according to local time.
Examples
--------
### Using getSeconds()
The second statement below assigns the value 30 to the variable `seconds`, based on the value of the [`Date`](../date) object `xmas95`.
```
const xmas95 = new Date("December 25, 1995 23:15:30");
const seconds = xmas95.getSeconds();
console.log(seconds); // 30
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getSeconds` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCSeconds()`](getutcseconds)
* [`Date.prototype.setSeconds()`](setseconds)
javascript Date.prototype.getUTCMilliseconds() Date.prototype.getUTCMilliseconds()
===================================
The `getUTCMilliseconds()` method returns the milliseconds portion of the time object's value according to universal time.
Try it
------
Syntax
------
```
getUTCMilliseconds()
```
### Return value
A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](gettime) method.
Examples
--------
### Using getUTCMilliseconds()
The following example assigns the milliseconds portion of the current time to the variable `milliseconds`.
```
const today = new Date();
const milliseconds = today.getUTCMilliseconds();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutcmilliseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutcmilliseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getMilliseconds()`](getmilliseconds)
* [`Date.prototype.setUTCMilliseconds()`](setutcmilliseconds)
| programming_docs |
javascript Date.prototype.setFullYear() Date.prototype.setFullYear()
============================
The `setFullYear()` method sets the full year for a specified date according to local time. Returns new timestamp.
Try it
------
Syntax
------
```
setFullYear(yearValue)
setFullYear(yearValue, monthValue)
setFullYear(yearValue, monthValue, dateValue)
```
### Parameters
`yearValue` An integer specifying the numeric value of the year, for example, 1995.
`monthValue` Optional. An integer between 0 and 11 representing the months January through December.
`dateValue` Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`getMonth()`](getmonth) and [`getDate()`](getdate) methods are used.
If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the [`Date`](../date) object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month.
Examples
--------
### Using setFullYear()
```
const theBigDay = new Date();
theBigDay.setFullYear(1997);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setfullyear](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setfullyear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCFullYear()`](getutcfullyear)
* [`Date.prototype.setUTCFullYear()`](setutcfullyear)
* [`Date.prototype.setYear()`](setyear)
javascript Date.prototype.getHours() Date.prototype.getHours()
=========================
The `getHours()` method returns the hour for the specified date, according to local time.
Try it
------
Syntax
------
```
getHours()
```
### Return value
An integer number, between 0 and 23, representing the hour for the given date according to local time.
Examples
--------
### Using getHours()
The second statement below assigns the value 23 to the variable `hours`, based on the value of the [`Date`](../date) object `xmas95`.
```
const xmas95 = new Date("December 25, 1995 23:15:30");
const hours = xmas95.getHours();
console.log(hours); // 23
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.gethours](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.gethours) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getHours` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCHours()`](getutchours)
* [`Date.prototype.setHours()`](sethours)
javascript Date.prototype.setUTCHours() Date.prototype.setUTCHours()
============================
The `setUTCHours()` method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated [`Date`](../date) instance.
Try it
------
Syntax
------
```
setUTCHours(hoursValue)
setUTCHours(hoursValue, minutesValue)
setUTCHours(hoursValue, minutesValue, secondsValue)
setUTCHours(hoursValue, minutesValue, secondsValue, msValue)
```
### Parameters
`hoursValue` An integer between 0 and 23, representing the hour.
`minutesValue` Optional. An integer between 0 and 59, representing the minutes.
`secondsValue` Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`.
`msValue` Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`.
### Return value
The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`getUTCMinutes()`](getutcminutes), [`getUTCSeconds()`](getutcseconds), and [`getUTCMilliseconds()`](getutcmilliseconds) methods are used.
If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds.
Examples
--------
### Using setUTCHours()
```
const theBigDay = new Date();
theBigDay.setUTCHours(8);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setutchours](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setutchours) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUTCHours` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCHours()`](getutchours)
* [`Date.prototype.setHours()`](sethours)
javascript Date.prototype.getUTCDay() Date.prototype.getUTCDay()
==========================
The `getUTCDay()` method returns the day of the week in the specified date according to universal time, where 0 represents Sunday.
Try it
------
Syntax
------
```
getUTCDay()
```
### Return value
A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Examples
--------
### Using getUTCDay()
The following example assigns the weekday portion of the current date to the variable `weekday`.
```
const today = new Date();
const weekday = today.getUTCDay();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutcday](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutcday) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCDay` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCDate()`](getutcdate)
* [`Date.prototype.getDay()`](getday)
* [`Date.prototype.setUTCDate()`](setutcdate)
javascript Date.prototype.setUTCDate() Date.prototype.setUTCDate()
===========================
The `setUTCDate()` method changes the day of the month of a given [`Date`](../date) instance, based on UTC time.
To instead change the day of the month for a given [`Date`](../date) instance based on local time, use the [`setDate()`](setdate) method.
Try it
------
Syntax
------
```
setUTCDate(dayValue)
```
### Parameters
`dayValue` An integer from 1 to 31, representing the day of the month.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the [`Date`](../date) object accordingly.
For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the [`Date`](../date) object is June, the day will be changed to 10 and the month will be incremented to July.
If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month.
Examples
--------
### Using setUTCDate()
```
const theBigDay = new Date();
theBigDay.setUTCDate(20);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setutcdate](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setutcdate) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUTCDate` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCDate()`](getutcdate)
* [`Date.prototype.setDate()`](setdate)
javascript Date.prototype.toUTCString() Date.prototype.toUTCString()
============================
The `toUTCString()` method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method.
Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values.
Try it
------
Syntax
------
```
toUTCString()
```
### Return value
A string representing the given date using the UTC time zone.
Description
-----------
The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where:
| Format String | Description |
| --- | --- |
| `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) |
| `dd` | Day of month, as two digits with leading zero if required |
| `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) |
| `yyyy` | Year, as four or more digits with leading zeroes if required |
| `hh` | Hour, as two digits with leading zero if required |
| `mm` | Minute, as two digits with leading zero if required |
| `ss` | Seconds, as two digits with leading zero if required |
### Aliasing
JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` β which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means:
```
Date.prototype.toGMTString.name === "toUTCString";
```
Examples
--------
### Using toUTCString()
```
const today = new Date("Wed, 14 Jun 2017 00:00:00 PDT");
const UTCstring = today.toUTCString(); // Wed, 14 Jun 2017 07:00:00 GMT
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.toutcstring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.toutcstring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toUTCString` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.toLocaleString()`](tolocalestring)
* [`Date.prototype.toDateString()`](todatestring)
* [`Date.prototype.toISOString()`](toisostring)
javascript Date.prototype.setMilliseconds() Date.prototype.setMilliseconds()
================================
The `setMilliseconds()` method sets the milliseconds for a specified date according to local time.
Try it
------
Syntax
------
```
setMilliseconds(millisecondsValue)
```
### Parameters
`millisecondsValue` A number between 0 and 999, representing the milliseconds.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you specify a number outside the expected range, the date information in the [`Date`](../date) object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds.
Examples
--------
### Using setMilliseconds()
```
const theBigDay = new Date();
theBigDay.setMilliseconds(100);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setmilliseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setmilliseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getMilliseconds()`](getmilliseconds)
* [`Date.prototype.setUTCMilliseconds()`](setutcmilliseconds)
javascript Date.prototype.getUTCDate() Date.prototype.getUTCDate()
===========================
The `getUTCDate()` method returns the day of the month (from 1 to 31) in the specified date according to universal time.
Try it
------
Syntax
------
```
getUTCDate()
```
### Return value
A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Examples
--------
### Using getUTCDate()
The following example assigns the day of month of the current date to the variable `dayOfMonth`.
```
const today = new Date();
const dayOfMonth = today.getUTCDate();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutcdate](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutcdate) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCDate` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCDate()`](getutcdate)
* [`Date.prototype.getDay()`](getday)
* [`Date.prototype.setUTCDate()`](setutcdate)
javascript Date.prototype.toDateString() Date.prototype.toDateString()
=============================
The `toDateString()` method returns the date portion of a [`Date`](../date) object interpreted in the local timezone in English.
Try it
------
Syntax
------
```
toDateString()
```
### Return value
A string representing the date portion of the given [`Date`](../date) object in human readable form in English.
Description
-----------
[`Date`](../date) instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the *date* part in English. It always uses the following format, separated by spaces:
1. First three letters of the week day name
2. First three letters of the month name
3. Two-digit day of the month, padded on the left a zero if necessary
4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign
For example: "Thu Jan 01 1970".
* If you want to get the *time* part, use [`toTimeString()`](totimestring).
* If you want to get both the date and time, use [`toString()`](tostring).
* If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](toutcstring).
* If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](tolocaledatestring).
Examples
--------
### A basic usage of toDateString()
```
const d = new Date(1993, 5, 28, 14, 39, 7);
console.log(d.toString()); // Mon Jun 28 1993 14:39:07 GMT-0600 (PDT)
console.log(d.toDateString()); // Mon Jun 28 1993
```
**Note:** Month are 0-indexed when used as an argument of [`Date`](../date) (thus 0 corresponds to January and 11 to December).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.todatestring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.todatestring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toDateString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.toLocaleDateString()`](tolocaledatestring)
* [`Date.prototype.toTimeString()`](totimestring)
* [`Date.prototype.toString()`](tostring)
javascript Date.prototype.getFullYear() Date.prototype.getFullYear()
============================
The `getFullYear()` method returns the year of the specified date according to local time.
Use this method instead of the [`getYear()`](getyear) method.
Try it
------
Syntax
------
```
getFullYear()
```
### Return value
A number corresponding to the year of the given date, according to local time.
Description
-----------
The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.
Examples
--------
### Using getFullYear()
The following example assigns the four-digit value of the current year to the variable `year`.
```
const today = new Date();
const year = today.getFullYear();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getfullyear](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getfullyear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCFullYear()`](getutcfullyear)
* [`Date.prototype.setFullYear()`](setfullyear)
* [`Date.prototype.getYear()`](getyear)
| programming_docs |
javascript Date.prototype.setUTCMilliseconds() Date.prototype.setUTCMilliseconds()
===================================
The `setUTCMilliseconds()` method sets the milliseconds for a specified date according to universal time.
Try it
------
Syntax
------
```
setUTCMilliseconds(millisecondsValue)
```
### Parameters
`millisecondsValue` A number between 0 and 999, representing the milliseconds.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the [`Date`](../date) object will be incremented by 1, and 100 will be used for milliseconds.
Examples
--------
### Using setUTCMilliseconds()
```
const theBigDay = new Date();
theBigDay.setUTCMilliseconds(500);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setutcmilliseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setutcmilliseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUTCMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCMilliseconds()`](getutcmilliseconds)
* [`Date.prototype.setMilliseconds()`](setmilliseconds)
javascript Date.prototype.getUTCHours() Date.prototype.getUTCHours()
============================
The `getUTCHours()` method returns the hours in the specified date according to universal time.
Try it
------
Syntax
------
```
getUTCHours()
```
### Return value
A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Examples
--------
### Using getUTCHours()
The following example assigns the hours portion of the current time to the variable `hours`.
```
const today = new Date();
const hours = today.getUTCHours();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutchours](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutchours) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCHours` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getHours()`](gethours)
* [`Date.prototype.setUTCHours()`](setutchours)
javascript Date.UTC() Date.UTC()
==========
The `Date.UTC()` static method accepts parameters similar to the [`Date`](../date) constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
Try it
------
Syntax
------
```
Date.UTC(year)
Date.UTC(year, monthIndex)
Date.UTC(year, monthIndex, day)
Date.UTC(year, monthIndex, day, hour)
Date.UTC(year, monthIndex, day, hour, minute)
Date.UTC(year, monthIndex, day, hour, minute, second)
Date.UTC(year, monthIndex, day, hour, minute, second, millisecond)
```
`year` Integer value representing the year.
Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](../date#interpretation_of_two-digit_years).
`monthIndex` Optional
An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. *(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)*
`day` Optional
An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`.
`hour` Optional
An integer between `0` and `23` representing the hours. If omitted, defaults to `0`.
`minute` Optional
An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`.
`second` Optional
An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`.
`millisecond` Optional
An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`.
### Return value
A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC.
Description
-----------
`UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time.
Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`.
The `UTC()` method differs from the [`Date`](../date) constructor in two ways:
1. `Date.UTC()` uses universal time instead of the local time.
2. `Date.UTC()` returns a time value as a number instead of creating a [`Date`](../date) object.
If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month.
`UTC()` is a static method of [`Date`](../date), so it's called as `Date.UTC()` rather than as a method of a [`Date`](../date) instance.
Examples
--------
### Using Date.UTC()
The following statement creates a [`Date`](../date) object with the arguments treated as UTC instead of local:
```
const utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.utc](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.utc) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `UTC` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
### Compatibility notes
#### Date.UTC() with fewer than two arguments
When providing less than two arguments to `Date.UTC()`, ECMAScript 2017 requires that [`NaN`](../nan) is returned. Engines that weren't supporting this behavior have been updated (see [bug 1050755](https://bugzilla.mozilla.org/show_bug.cgi?id=1050755), [ecma-262 #642](https://github.com/tc39/ecma262/pull/642)).
```
Date.UTC();
Date.UTC(1);
// Safari: NaN
// Chrome/Opera/V8: NaN
// Firefox <54: non-NaN
// Firefox 54+: NaN
// IE: non-NaN
// Edge: NaN
```
See also
--------
* [`Date.parse()`](parse)
* [`Date`](../date)
javascript Date.prototype.getMinutes() Date.prototype.getMinutes()
===========================
The `getMinutes()` method returns the minutes in the specified date according to local time.
Try it
------
Syntax
------
```
getMinutes()
```
### Return value
An integer number, between 0 and 59, representing the minutes in the given date according to local time.
Examples
--------
### Using getMinutes()
The second statement below assigns the value 15 to the variable `minutes`, based on the value of the [`Date`](../date) object `xmas95`.
```
const xmas95 = new Date("December 25, 1995 23:15:30");
const minutes = xmas95.getMinutes();
console.log(minutes); // 15
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getminutes](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getminutes) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getMinutes` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCMinutes()`](getutcminutes)
* [`Date.prototype.setMinutes()`](setminutes)
javascript Date.prototype.setYear() Date.prototype.setYear()
========================
**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.
The legacy `setYear()` method sets the year for a specified date according to local time.
However, the way the legacy `setYear()` method sets year values is different from how the preferred [`setFullYear()`](setfullyear) method sets year values β and in some cases, also different from how `new Date()` and [`Date.parse()`](parse) set year values. Specifically, given two-digit numbers, such as `22` and `61`:
* `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](parse)).
* [`setFullYear()`](setfullyear) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`.
Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`setFullYear()`](setfullyear) method.
Syntax
------
```
setYear(yearValue)
```
### Parameters
`yearValue` An integer.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`.
Examples
--------
### Using setYear()
The first two lines set the year to 1996. The third sets the year to 2000.
```
const theBigDay = new Date();
theBigDay.setYear(96);
theBigDay.setYear(1996);
theBigDay.setYear(2000);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setyear](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-date.prototype.setyear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setYear` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Date.prototype.setYear` in `core-js`](https://github.com/zloirock/core-js#ecmascript-date)
* [`Date.prototype.getFullYear()`](getfullyear)
* [`Date.prototype.getUTCFullYear()`](getutcfullyear)
* [`Date.prototype.setFullYear()`](setfullyear)
* [`Date.prototype.setUTCFullYear()`](setutcfullyear)
javascript Date.prototype.setSeconds() Date.prototype.setSeconds()
===========================
The `setSeconds()` method sets the seconds for a specified date according to local time.
Try it
------
Syntax
------
```
setSeconds(secondsValue)
setSeconds(secondsValue, msValue)
```
### Parameters
`secondsValue` An integer between 0 and 59, representing the seconds.
`msValue` Optional
Optional. A number between 0 and 999, representing the milliseconds.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `msValue` parameter, the value returned from the [`getMilliseconds()`](getmilliseconds) method is used.
If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the [`Date`](../date) object will be incremented by 1, and 40 will be used for seconds.
Examples
--------
### Using setSeconds()
```
const theBigDay = new Date();
theBigDay.setSeconds(30);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setseconds](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setseconds) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setSeconds` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getSeconds()`](getseconds)
* [`Date.prototype.setUTCSeconds()`](setutcseconds)
javascript Date.prototype.getDate() Date.prototype.getDate()
========================
The `getDate()` method returns the day of the month for the specified date according to local time.
Try it
------
Syntax
------
```
getDate()
```
### Return value
An integer number, between 1 and 31, representing the day of the month for the given date according to local time.
Examples
--------
### Using getDate()
The second statement below assigns the value 25 to the variable `day`, based on the value of the [`Date`](../date) object `xmas95`.
```
const xmas95 = new Date("December 25, 1995 23:15:30");
const day = xmas95.getDate();
console.log(day); // 25
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getdate](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getdate) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getDate` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCDate()`](getutcdate)
* [`Date.prototype.getUTCDay()`](getutcday)
* [`Date.prototype.setDate()`](setdate)
javascript Date.prototype.setHours() Date.prototype.setHours()
=========================
The `setHours()` method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated [`Date`](../date) instance.
Try it
------
Syntax
------
```
setHours(hoursValue)
setHours(hoursValue, minutesValue)
setHours(hoursValue, minutesValue, secondsValue)
setHours(hoursValue, minutesValue, secondsValue, msValue)
```
### Parameters
`hoursValue` Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours.
`minutesValue` Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes.
`secondsValue` Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`.
`msValue` Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`.
### Return value
The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`getMinutes()`](getminutes), [`getSeconds()`](getseconds), and [`getMilliseconds()`](getmilliseconds) methods are used.
If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds.
Examples
--------
### Using setHours()
```
const theBigDay = new Date();
theBigDay.setHours(7);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.sethours](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.sethours) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setHours` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getHours()`](gethours)
* [`Date.prototype.setUTCHours()`](setutchours)
javascript Date.prototype.toTimeString() Date.prototype.toTimeString()
=============================
The `toTimeString()` method returns the time portion of a [`Date`](../date) object interpreted in the local timezone in English.
Try it
------
Syntax
------
```
toTimeString()
```
### Return value
A string representing the time portion of the given date in human readable form in English.
Description
-----------
[`Date`](../date) instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the *time* part in English. It always uses the format of `hh:mm:ss GMTΒ±xxxx (TZ)`, where:
| Format String | Description |
| --- | --- |
| `hh` | Hour, as two digits with leading zero if required |
| `mm` | Minute, as two digits with leading zero if required |
| `ss` | Seconds, as two digits with leading zero if required |
| `Β±xxxx` | The local timezone's offset β two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) |
| `TZ` | The timezone's name (e.g. `PDT`, `PST`) |
For example: "04:42:04 GMT+0000 (Coordinated Universal Time)".
* If you want to get the *date* part, use [`toDateString()`](todatestring).
* If you want to get both the date and time, use [`toString()`](tostring).
* If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](toutcstring).
* If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](tolocaletimestring).
Examples
--------
### A basic usage of toTimeString()
```
const d = new Date(1993, 6, 28, 14, 39, 7);
console.log(d.toString()); // Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
console.log(d.toTimeString()); // 14:39:07 GMT-0600 (PDT)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.totimestring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.totimestring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toTimeString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.toLocaleTimeString()`](tolocaletimestring)
* [`Date.prototype.toDateString()`](todatestring)
* [`Date.prototype.toString()`](tostring)
| programming_docs |
javascript Date.prototype.setUTCMinutes() Date.prototype.setUTCMinutes()
==============================
The `setUTCMinutes()` method sets the minutes for a specified date according to universal time.
Try it
------
Syntax
------
```
setUTCMinutes(minutesValue)
setUTCMinutes(minutesValue, secondsValue)
setUTCMinutes(minutesValue, secondsValue, msValue)
```
### Parameters
`minutesValue` An integer between 0 and 59, representing the minutes.
`secondsValue` Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`.
`msValue` Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`getUTCSeconds()`](getutcseconds) and [`getUTCMilliseconds()`](getutcmilliseconds) methods are used.
If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds.
Examples
--------
### Using setUTCMinutes()
```
const theBigDay = new Date();
theBigDay.setUTCMinutes(43);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setutcminutes](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setutcminutes) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUTCMinutes` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCMinutes()`](getutcminutes)
* [`Date.prototype.setMinutes()`](setminutes)
javascript Date.prototype.getUTCMinutes() Date.prototype.getUTCMinutes()
==============================
The `getUTCMinutes()` method returns the minutes in the specified date according to universal time.
Try it
------
Syntax
------
```
getUTCMinutes()
```
### Return value
A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Examples
--------
### Using getUTCMinutes()
The following example assigns the minutes portion of the current time to the variable `minutes`.
```
const today = new Date();
const minutes = today.getUTCMinutes();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutcminutes](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutcminutes) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCMinutes` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getMinutes()`](getminutes)
* [`Date.prototype.setUTCMinutes()`](setutcminutes)
javascript Date.prototype.getYear() Date.prototype.getYear()
========================
**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.
The `getYear()` method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`getFullYear()`](getfullyear) method.
Syntax
------
```
getYear()
```
### Return value
A number representing the year of the given date, according to local time, minus 1900.
Description
-----------
* For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126.
* For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76.
* For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100.
To take into account years before and after 2000, you should use [`getFullYear()`](getfullyear) instead of `getYear()` so that the year is specified in full.
Examples
--------
### Years between 1900 and 1999
The second statement assigns the value 95 to the variable `year`.
```
const xmas = new Date("December 25, 1995 23:15:00");
const year = xmas.getYear(); // returns 95
```
### Years above 1999
The second statement assigns the value 100 to the variable `year`.
```
const xmas = new Date("December 25, 2000 23:15:00");
const year = xmas.getYear(); // returns 100
```
### Years below 1900
The second statement assigns the value -100 to the variable `year`.
```
const xmas = new Date("December 25, 1800 23:15:00");
const year = xmas.getYear(); // returns -100
```
### Setting and getting a year between 1900 and 1999
The third statement assigns the value 95 to the variable `year`, representing the year 1995.
```
const xmas = new Date("December 25, 2015 23:15:00");
xmas.setYear(95);
const year = xmas.getYear(); // returns 95
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getyear](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-date.prototype.getyear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getYear` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Date.prototype.getYear` in `core-js`](https://github.com/zloirock/core-js#ecmascript-date)
* [`Date.prototype.getFullYear()`](getfullyear)
* [`Date.prototype.getUTCFullYear()`](getutcfullyear)
* [`Date.prototype.setYear()`](setyear)
javascript Date.prototype.setDate() Date.prototype.setDate()
========================
The `setDate()` method changes the day of the month of a given [`Date`](../date) instance, based on local time.
To instead change the day of the month for a given [`Date`](../date) instance based on UTC time, use the [`setUTCDate()`](setutcdate) method.
Try it
------
Syntax
------
```
setDate(dayValue)
```
### Parameters
`dayValue` An integer representing the day of the month.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the [`Date`](../date) object is also changed in place).
Description
-----------
If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the [`Date`](../date) object accordingly.
For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the [`Date`](../date) object is June, the day will be changed to 10 and the month will be incremented to July.
If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month.
Examples
--------
### Using setDate()
```
const theBigDay = new Date(1962, 6, 7, 12); // noon of 1962-07-07 (7th of July 1962, month is 0-indexed)
const theBigDay2 = new Date(theBigDay).setDate(24); // 1962-07-24 (24th of July 1962)
const theBigDay3 = new Date(theBigDay).setDate(32); // 1962-08-01 (1st of August 1962)
const theBigDay4 = new Date(theBigDay).setDate(22); // 1962-07-22 (22nd of July 1962)
const theBigDay5 = new Date(theBigDay).setDate(0); // 1962-06-30 (30th of June 1962)
const theBigDay6 = new Date(theBigDay).setDate(98); // 1962-10-06 (6th of October 1962)
const theBigDay7 = new Date(theBigDay).setDate(-50); // 1962-05-11 (11th of May 1962)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setdate](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setdate) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setDate` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date()`](date)
* [`Date.prototype.getDate()`](getdate)
* [`Date.prototype.setUTCDate()`](setutcdate)
javascript Date.prototype.toString() Date.prototype.toString()
=========================
The `toString()` method returns a string representing the specified [`Date`](../date) object interpreted in the local timezone.
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the given date.
Description
-----------
The [`Date`](../date) object overrides the `toString()` method of [`Object`](../object). `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time β it joins the string representation specified in [`toDateString()`](todatestring) and [`toTimeString()`](totimestring) together, adding a space in between.
For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)"
The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`.
`Date.prototype.toString()` must be called on [`Date`](../date) instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../typeerror) is thrown.
* If you only want to get the *date* part, use [`toDateString()`](todatestring).
* If you only want to get the *time* part, use [`toTimeString()`](totimestring).
* If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](toutcstring).
* If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](tolocalestring).
Examples
--------
### Using toString()
```
const x = new Date();
console.log(x.toString()); // Mon Sep 08 1998 14:36:22 GMT-0700 (PDT)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.tostring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.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 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.prototype.toString()`](../object/tostring)
* [`Date.prototype.toDateString()`](todatestring)
* [`Date.prototype.toLocaleString()`](tolocalestring)
* [`Date.prototype.toTimeString()`](totimestring)
javascript Date.parse() Date.parse()
============
The `Date.parse()` static method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.
Try it
------
Syntax
------
```
Date.parse(dateString)
```
### Parameters
`dateString` A string representing [a simplification of the ISO 8601 calendar date extended format](#date_time_string_format). (Other formats may be used, but results are implementation-dependent.)
### Return value
A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../nan) is returned.
Description
-----------
The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](settime) method and the [`Date`](../date) object.
### Date Time String Format
The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.)
For example, `"2011-10-10"` (*date-only* form), `"2011-10-10T14:48:00"` (*date-time* form), or `"2011-10-10T14:48:00.000+09:00"` (*date-time* form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.
While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`.
Because `parse()` is a static method of [`Date`](../date), it is called as `Date.parse()` rather than as a method of a [`Date`](../date) instance.
### Fall-back to implementation-specific date formats
**Note:** This section contains implementation-specific behavior that can be inconsistent across implementations.
The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementationβspecific heuristics or implementationβspecific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../nan).
However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../nan), depending on the browser and values provided, e.g.:
```
// Non-ISO string with invalid date values
new Date("23/25/2014");
```
will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7.
However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../nan):
```
// ISO string with invalid values
new Date("2014-25-23").toISOString();
// throws "RangeError: invalid date"
```
SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works.
```
new Date("10 06 2014");
```
will be treated as a local date of 6 October, 2014, and not 10 June, 2014.
Other examples:
```
new Date("foo-bar 2014").toString();
// returns: "Invalid Date"
Date.parse("foo-bar 2014");
// returns: NaN
```
### Differences in assumed time zone
**Note:** This section contains implementation-specific behavior that can be inconsistent across implementations.
Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore [`Date`](../date) objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.
Examples
--------
### Using Date.parse()
The following calls all return `1546300800000`. The first will imply UTC time, and the others are specifying UTC timezone via the ISO date specification (`Z` and `+00:00`).
```
Date.parse("2019-01-01");
Date.parse("2019-01-01T00:00:00.000Z");
Date.parse("2019-01-01T00:00:00.000+00:00");
```
The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system.
```
Date.parse("2019-01-01T00:00:00");
```
### Non-standard date strings
**Note:** This section contains implementation-specific behavior that can be inconsistent across implementations.
If `ipoDate` is an existing [`Date`](../date) object, it can be set to August 9, 1995 (local time) as follows:
```
ipoDate.setTime(Date.parse("Aug 9, 1995"));
```
Some other examples of parsing non-standard date strings:
```
Date.parse("Aug 9, 1995");
```
Returns `807937200000` in time zone GMT-0300, and other values in other time zones, since the string does not specify a time zone and is not ISO format, therefore the time zone defaults to local.
```
Date.parse("Wed, 09 Aug 1995 00:00:00 GMT");
```
Returns `807926400000` no matter the local time zone as GMT (UTC) is provided.
```
Date.parse("Wed, 09 Aug 1995 00:00:00");
```
Returns `807937200000` in time zone GMT-0300, and other values in other time zones, since there is no time zone specifier in the argument and it is not ISO format, so is treated as local.
```
Date.parse("Thu, 01 Jan 1970 00:00:00 GMT");
```
Returns `0` no matter the local time zone as a time zone GMT (UTC) is provided.
```
Date.parse("Thu, 01 Jan 1970 00:00:00");
```
Returns `14400000` in time zone GMT-0400, and other values in other time zones, since no time zone is provided and the string is not in ISO format, therefore the local time zone is used.
```
Date.parse("Thu, 01 Jan 1970 00:00:00 GMT-0400");
```
Returns `14400000` no matter the local time zone as a time zone GMT (UTC) is provided.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.parse](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.parse) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `parse` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `iso_8601` | 6 | 12 | 4 | 9 | 6 | 5.1 | β€37 | 18 | 4 | 10.1 | 5 | 1.0 | 1.0 | 0.12.0 |
### Compatibility notes
* Firefox 49 changed the parsing of 2-digit years to be aligned with the Google Chrome browser instead of Internet Explorer. Now, 2-digit years that are less than `50` are parsed as 21st century years. For example, `04/16/17`, previously parsed as April 16, 1917, will be April 16, 2017 now. To avoid any interoperability issues or ambiguous years, it is recommended to use the ISO 8601 format like `"2017-04-16"` ([bug 1265136](https://bugzilla.mozilla.org/show_bug.cgi?id=1265136)).
* Google Chrome will accept a numerical string as a valid `dateString` parameter. This means that, for instance, while `!!Date.parse("42")` evaluates to `false` in Firefox, it evaluates to `true` in Google Chrome because `"42"` is interpreted as the first of January 2042.
See also
--------
* [`Date.UTC()`](utc)
| programming_docs |
javascript Date.prototype.getUTCFullYear() Date.prototype.getUTCFullYear()
===============================
The `getUTCFullYear()` method returns the year in the specified date according to universal time.
Try it
------
Syntax
------
```
getUTCFullYear()
```
### Return value
A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](../number/nan) if the `Date` object doesn't represent a valid date.
Description
-----------
The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995.
Examples
--------
### Using getUTCFullYear()
The following example assigns the four-digit value of the current year to the variable `year`.
```
const today = new Date();
const year = today.getUTCFullYear();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getutcfullyear](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getutcfullyear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUTCFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getFullYear()`](getfullyear)
* [`Date.prototype.setFullYear()`](setfullyear)
javascript Date.prototype.toISOString() Date.prototype.toISOString()
============================
The `toISOString()` method returns a string in *simplified* extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `Β±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`.
Try it
------
Syntax
------
```
toISOString()
```
### Return value
A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](parse#date_time_string_format).
Examples
--------
### Using toISOString()
```
const today = new Date("05 October 2011 14:48 UTC");
console.log(today.toISOString()); // Returns 2011-10-05T14:48:00.000Z
```
The above example uses parsing of a nonβstandard string value that may not be correctly parsed in nonβMozilla browsers.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.toisostring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.toisostring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toISOString` | 3 | 12 | 1 | 9 | 10.5 | 4 | β€37 | 18 | 4 | 11 | 3.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.toLocaleDateString()`](tolocaledatestring)
* [`Date.prototype.toTimeString()`](totimestring)
* [`Date.prototype.toUTCString()`](toutcstring)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/date.polyfill.js)
javascript Date() constructor Date() constructor
==================
The `Date()` constructor can create a [`Date`](../date) instance or return a string representing the current time.
Try it
------
Syntax
------
```
new Date()
new Date(value)
new Date(dateString)
new Date(dateObject)
new Date(year, monthIndex)
new Date(year, monthIndex, day)
new Date(year, monthIndex, day, hours)
new Date(year, monthIndex, day, hours, minutes)
new Date(year, monthIndex, day, hours, minutes, seconds)
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
Date()
```
**Note:** `Date()` can be called with or without [`new`](../../operators/new), but with different effects. See [Return value](#return_value).
### Parameters
There are five basic forms for the `Date()` constructor:
#### No parameters
When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation.
#### Time value or timestamp number
`value` An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second.
#### Date string
`dateString` A string value representing a date, in a format recognized by the [`Date.parse()`](parse) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).)
**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 (`YYYY-MM-DDTHH:mm:ss.sssZ`) β the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated.
Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types.
#### Date object
`dateObject` An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called.
When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp.
#### Individual date and time component values
Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC.
If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020.
Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020.
`year` Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](../date#interpretation_of_two-digit_years).
`monthIndex` Integer value representing the month, beginning with `0` for January to `11` for December.
`day` Optional
Integer value representing the day of the month. The default is `1`.
`hours` Optional
Integer value between `0` and `23` representing the hour of the day. Defaults to `0`.
`minutes` Optional
Integer value representing the minute segment of a time. The default is `0` minutes past the hour.
`seconds` Optional
Integer value representing the second segment of a time. The default is `0` seconds past the minute.
`milliseconds` Optional
Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second.
### Return value
Calling `new Date()` (the `Date()` constructor) returns a [`Date`](../date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](tostring) method returns the literal string `Invalid Date`.
Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string β or even called with any arbitrary object or other primitive as an argument β it always returns a string representation of the current date and time.
Examples
--------
### Several ways to create a Date object
The following examples show several ways to create JavaScript dates:
```
const today = new Date();
const birthday = new Date("December 17, 1995 03:24:00"); // DISCOURAGED: may not work in all runtimes
const birthday = new Date("1995-12-17T03:24:00"); // This is ISO-8601-compliant and will work reliably
const birthday = new Date(1995, 11, 17); // the month is 0-indexed
const birthday = new Date(1995, 11, 17, 3, 24, 0);
const birthday = new Date(628021800000); // passing epoch timestamp
```
### Passing a non-Date, non-string, non-number value
If the `Date()` constructor is called with one parameter which is not a `Date` instance, it will be coerced to a primitive and then checked whether it's a string. For example, `new Date(undefined)` is different from `new Date()`:
```
console.log(new Date(undefined)); // Invalid Date
```
This is because `undefined` is already a primitive but not a string, so it will be coerced to a number, which is [`NaN`](../nan) and therefore not a valid timestamp. On the other hand, `null` will be coerced to `0`.
```
console.log(new Date(null)); // 1970-01-01T00:00:00.000Z
```
[Arrays](../array) would be coerced to a string via [`Array.prototype.toString()`](../array/tostring), which joins the elements with commas. However, the resulting string for any array with more than one element is not a valid ISO 8601 date string, so its parsing behavior would be implementation-defined. `Date()`
```
console.log(new Date(["2020-06-19", "17:13"]));
// 2020-06-19T17:13:00.000Z in Chrome, since it recognizes "2020-06-19,17:13"
// "Invalid Date" in Firefox
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date-constructor](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-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 |
| `Date` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date`](../date)
javascript Date.prototype.setUTCMonth() Date.prototype.setUTCMonth()
============================
The `setUTCMonth()` method sets the month for a specified date according to universal time.
Try it
------
Syntax
------
```
setUTCMonth(monthValue)
setUTCMonth(monthValue, dayValue)
```
### Parameters
`monthValue` An integer between 0 and 11, representing the months January through December.
`dayValue` Optional. An integer from 1 to 31, representing the day of the month.
### Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
-----------
If you do not specify the `dayValue` parameter, the value returned from the [`getUTCDate()`](getutcdate) method is used.
If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the [`Date`](../date) object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month.
Examples
--------
### Using setUTCMonth()
```
const theBigDay = new Date();
theBigDay.setUTCMonth(11);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.setutcmonth](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setutcmonth) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUTCMonth` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCMonth()`](getutcmonth)
* [`Date.prototype.setMonth()`](setmonth)
javascript Date.prototype.getMonth() Date.prototype.getMonth()
=========================
The `getMonth()` method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).
Try it
------
Syntax
------
```
getMonth()
```
### Return value
An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on.
Examples
--------
### Using getMonth()
The second statement below assigns the value 11 to the variable `month`, based on the value of the [`Date`](../date) object `xmas95`.
```
const xmas95 = new Date("December 25, 1995 23:15:30");
const month = xmas95.getMonth();
console.log(month); // 11
```
**Note:** If needed, the full name of a month (`January` for example) can be obtained by using [`Intl.DateTimeFormat()`](../intl/datetimeformat#using_options) with an `options` parameter. Using this method, internationalization is made easier:
```
const options = { month: "long" };
console.log(new Intl.DateTimeFormat("en-US", options).format(Xmas95));
// December
console.log(new Intl.DateTimeFormat("de-DE", options).format(Xmas95));
// Dezember
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.getmonth](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.getmonth) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getMonth` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.getUTCMonth()`](getutcmonth)
* [`Date.prototype.setMonth()`](setmonth)
javascript Date.prototype.getTimezoneOffset() Date.prototype.getTimezoneOffset()
==================================
The `getTimezoneOffset()` method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.
Try it
------
Syntax
------
```
getTimezoneOffset()
```
### Return value
The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data.
Description
-----------
`date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone β that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in.
### Negative values and positive values
The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned.
| Current time zone | Return value |
| --- | --- |
| UTC-8 | 480 |
| UTC | 0 |
| UTC+3 | -180 |
### Varied results in Daylight Saving Time (DST) regions
In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform.
**Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run β its behavior is always consistent when running in the same region. Only the value of `date` affects the result.
In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero.
Examples
--------
### Using getTimezoneOffset()
```
// Create a Date instance for the current time
const currentLocalDate = new Date();
// Create a Date instance for 03:24 GMT-0200 on May 1st in 2016
const laborDay2016at0324GMTminus2 = new Date("2016-05-01T03:24:00-02:00");
currentLocalDate.getTimezoneOffset() ===
laborDay2016at0324GMTminus2.getTimezoneOffset();
// true, always, in any timezone that doesn't annually shift in and out of DST
// false, sometimes, in any timezone that annually shifts in and out of DST
```
### getTimezoneOffset() and DST
In regions that use DST, the return value may change based on the time of the year `date` is in. Below is the output in a runtime in New York, where the timezone is UTC-05:00.
```
const nyOffsetSummer = new Date("2022-02-01").getTimezoneOffset(); // 300
const nyOffsetWinter = new Date("2022-08-01").getTimezoneOffset(); // 240
```
### getTimezoneOffset() and historical data
Due to historical reasons, the timezone a region is in can be constantly changing, even disregarding DST. For example, below is the output in a runtime in Shanghai, where the timezone is UTC+08:00.
```
const shModernOffset = new Date("2022-01-27").getTimezoneOffset(); // -480
const shHistoricalOffset = new Date("1943-01-27").getTimezoneOffset(); // -540
```
This is because during the [Sino-Japanese War](https://en.wikipedia.org/wiki/Second_Sino-Japanese_War) when Shanghai was under Japanese control, the timezone was changed to UTC+09:00 to align with Japan's (in effect, it was a "year-round DST"), and this was recorded in the IANA database.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.gettimezoneoffset](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.gettimezoneoffset) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getTimezoneOffset` | 1 | 12 | 1 | 5 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date`](../date)
| programming_docs |
javascript Date.prototype.toJSON() Date.prototype.toJSON()
=======================
The `toJSON()` method returns a string representation of the [`Date`](../date) object.
Try it
------
Syntax
------
```
toJSON()
```
### Return value
A string representation of the given date.
Description
-----------
[`Date`](../date) instances refer to a specific point in time. `toJSON()` calls the object's [`toISOString()`](toisostring) method, which returns a string representing the [`Date`](../date) object's value. This method is generally intended to, by default, usefully serialize [`Date`](../date) objects during [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](date) or [`Date.parse()`](parse) as the reviver of [`JSON.parse()`](../json/parse).
The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[@@toPrimitive]()`](../symbol/toprimitive) (with `"number"` as hint), [`valueOf()`](../object/valueof), and [`toString()`](../object/tostring) methods, in that order. If the result is a [non-finite](../number/isfinite) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](valueof) returns [`NaN`](../nan).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned.
Note that the method does not check whether the `this` value is a valid [`Date`](../date) object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics.
Examples
--------
### Using toJSON()
```
const jsonDate = new Date().toJSON();
const backToDate = new Date(jsonDate);
console.log(jsonDate); // 2015-10-26T07:46:36.611Z
```
### Serialization round-tripping
When parsing JSON containing date strings, you can use [`Date.parse()`](parse) to revive them into the original date objects.
```
const fileData = {
author: "Maria",
title: "Date.prototype.toJSON()",
createdAt: new Date(2019, 3, 15),
updatedAt: new Date(2020, 6, 26),
};
const response = JSON.stringify(fileData);
// Imagine transmission through network
const data = JSON.parse(response, (key, value) => {
if (key === "createdAt" || key === "updatedAt") {
return Date.parse(value);
}
return value;
});
console.log(data);
```
**Note:** The reviver of `JSON.parse()` must be specific to the payload shape you expect, because the serialization is *lossy*: it's not possible to distinguish between a string that represents a Date and a normal string.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date.prototype.tojson](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.tojson) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toJSON` | 3 | 12 | 1 | 8 | 10.5 | 4 | β€37 | 18 | 4 | 11 | 3.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.toLocaleDateString()`](tolocaledatestring)
* [`Date.prototype.toTimeString()`](totimestring)
* [`Date.prototype.toUTCString()`](toutcstring)
javascript Reflect.has() Reflect.has()
=============
The `Reflect.has()` static method works like the [`in` operator](../../operators/in) as a function.
Try it
------
Syntax
------
```
Reflect.has(target, propertyKey)
```
### Parameters
`target` The target object in which to look for the property.
`propertyKey` The name of the property to check.
### Return value
A [`Boolean`](../boolean) indicating whether or not the `target` has the property.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](../../operators/in) as a function.
Examples
--------
### Using Reflect.has()
```
Reflect.has({x: 0}, 'x') // true
Reflect.has({x: 0}, 'y') // false
// returns true for properties in the prototype chain
Reflect.has({x: 0}, 'toString')
// Proxy with .has() handler method
obj = new Proxy({}, {
has(t, k) { return k.startsWith('door') }
});
Reflect.has(obj, 'doorbell') // true
Reflect.has(obj, 'dormitory') // false
```
`Reflect.has` returns `true` for any inherited properties, like the [`in` operator](../../operators/in):
```
const a = {foo: 123}
const b = {\_\_proto\_\_: a}
const c = {\_\_proto\_\_: b}
// The prototype chain is: c -> b -> a
Reflect.has(c, 'foo') // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.has](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.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` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.has` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`in` operator](../../operators/in)
javascript Comparing Reflect and Object methods Comparing Reflect and Object methods
====================================
The [`Reflect`](../reflect) object is a built-in object that provides methods to interface with JavaScript objects. Some of the static functions that exist on `Reflect` also correspond to methods available on [`Object`](../object). Although some of the methods appear to be similar in their behavior, there are often subtle differences between them.
The table below details the differences between the methods available on the `Object` and `Reflect` APIs. Please note that if a method does not exist in an API, it is marked as N/A.
| Method Name | `Object` | `Reflect` |
| --- | --- | --- |
| `defineProperty()` | [`Object.defineProperty()`](../object/defineproperty) returns the object that was passed to the function. Throws a `TypeError` if the property was not successfully defined on the object. | [`Reflect.defineProperty()`](defineproperty) returns `true` if the property was defined on the object and `false` if it was not. |
| `defineProperties()` | [`Object.defineProperties()`](../object/defineproperties) returns the objects that were passed to the function. Throws a `TypeError` if any properties were not successfully defined on the object. | N/A |
| `has()` | N/A | [`Reflect.has()`](has) returns `true` if the property exists on the object or on its prototype chain or `false` otherwise, similar to the [`in` operator](/en-US/docs/Web/JavaScript/Reference/Operators/in). Throws a `TypeError` if the target was not an `Object`. |
| `get()` | N/A | [`Reflect.get()`](get) returns the value of the property. Throws a `TypeError` if the target was not an `Object`. |
| `set()` | N/A | [`Reflect.set()`](set) returns `true` if the property was set successfully on the object and `false` if it was not. Throws a `TypeError` if the target was not an `Object`. |
| `deleteProperty()` | N/A | [`Reflect.deleteProperty()`](deleteproperty) returns `true` if the property was deleted from the object and `false` if it was not. |
| `getOwnPropertyDescriptor()` | [`Object.getOwnPropertyDescriptor()`](../object/getownpropertydescriptor) returns a property descriptor of the given property if it exists on the object argument passed in, and returns `undefined` if it does not exist. However, if an object is not passed in as the first argument, it will be coerced into an object. | [`Reflect.getOwnPropertyDescriptor()`](getownpropertydescriptor) returns a property descriptor of the given property if it exists on the object. Returns `undefined` if it does not exist, and a `TypeError` if anything other than an object (a primitive) is passed in as the first argument. |
| `getOwnPropertyDescriptors()` | [`Object.getOwnPropertyDescriptors()`](../object/getownpropertydescriptors) returns an object containing a property descriptor of each passed-in object. Returns an empty object if the passed-in object has no owned property descriptors. | N/A |
| `getPrototypeOf()` | [`Object.getPrototypeOf()`](../object/getprototypeof) returns the prototype of the given object. Returns `null` if there are no inherited properties. Throws a `TypeError` for non-objects in ES5, but coerces non-objects in ES2015. | [`Reflect.getPrototypeOf()`](getprototypeof) returns the prototype of the given object. Returns `null` if there are no inherited properties, and throws a `TypeError` for non-objects. |
| `setPrototypeOf()` | [`Object.setPrototypeOf()`](../object/setprototypeof) returns the object itself if its prototype was set successfully. Throws a `TypeError` if the prototype being set was anything other than an `Object` or `null`, or if the prototype for the object being modified is non-extensible. | [`Reflect.setPrototypeOf()`](setprototypeof) returns `true` if the prototype was successfully set on the object and `false` if it wasn't (including if the prototype is non-extensible). Throws a `TypeError` if the target passed in was not an `Object`, or if the prototype being set was anything other than an `Object` or `null`. |
| `isExtensible()` | [`Object.isExtensible()`](../object/isextensible) returns `true` if the object is extensible, and `false` if it is not. Throws a `TypeError` in ES5 if the first argument is not an object (a primitive). In ES2015, it will be coerced into a non-extensible, ordinary object and will return `false`. | [`Reflect.isExtensible()`](isextensible) returns `true` if the object is extensible, and `false` if it is not. Throws a `TypeError` if the first argument is not an object (a primitive). |
| `preventExtensions()` | [`Object.preventExtensions()`](../object/preventextensions) returns the object that is being made non-extensible. Throws a `TypeError`in ES5 if the argument is not an object (a primitive). In ES2015, treats the argument as a non-extensible, ordinary object and returns the object itself. | [`Reflect.preventExtensions()`](preventextensions) returns `true` if the object has been made non-extensible, and `false` if it has not. Throws a `TypeError` if the argument is not an object (a primitive). |
| `keys()` | [`Object.keys()`](../object/keys) returns an `Array` of strings that map to the target object's own (enumerable) property keys. Throws a `TypeError` in ES5 if the target is not an object, but coerces non-object targets into objects in ES2015. | N/A |
| `ownKeys()` | N/A | [`Reflect.ownKeys()`](ownkeys) returns an `Array` of property names that map to the target object's own property keys. Throws a `TypeError` if the target is not an `Object`. |
javascript Reflect.apply() Reflect.apply()
===============
The `Reflect.apply()` static method calls a target function with arguments as specified.
Try it
------
Syntax
------
```
Reflect.apply(target, thisArgument, argumentsList)
```
### Parameters
`target` The target function to call.
`thisArgument` The value of `this` provided for the call to `target`.
`argumentsList` An array-like object specifying the arguments with which `target` should be called.
### Return value
The result of calling the given `target` function with the specified `this` value and arguments.
### Exceptions
A [`TypeError`](../typeerror), if the `target` is not callable.
Description
-----------
In ES5, you typically use the [`Function.prototype.apply()`](../function/apply) method to call a function with a given `this` value and `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.apply.call(Math.floor, undefined, [1.75]);
```
With `Reflect.apply()` this becomes less verbose and easier to understand.
Examples
--------
### Using Reflect.apply()
```
Reflect.apply(Math.floor, undefined, [1.75]);
// 1;
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
// "hello"
Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
// 4
Reflect.apply("".charAt, "ponies", [3]);
// "i"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.apply](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.apply) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.apply` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Function.prototype.apply()`](../function/apply)
javascript Reflect.setPrototypeOf() Reflect.setPrototypeOf()
========================
The `Reflect.setPrototypeOf()` static method is the same method as [`Object.setPrototypeOf()`](../object/setprototypeof), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](../../operators/null), and returns `true` if the operation was successful, or `false` otherwise.
Try it
------
Syntax
------
```
Reflect.setPrototypeOf(target, prototype)
```
### Parameters
`target` The target object of which to set the prototype.
`prototype` The object's new prototype (an object or [`null`](../../operators/null)).
### Return value
A [`Boolean`](../boolean) indicating whether or not the prototype was successfully set.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object) or if `prototype` is neither an object nor [`null`](../../operators/null).
Description
-----------
The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object.
Examples
--------
### Using Reflect.setPrototypeOf()
```
Reflect.setPrototypeOf({}, Object.prototype); // true
// It can change an object's [[Prototype]] to null.
Reflect.setPrototypeOf({}, null); // true
// Returns false if target is not extensible.
Reflect.setPrototypeOf(Object.freeze({}), null); // false
// Returns false if it cause a prototype chain cycle.
const target = {};
const proto = Object.create(target);
Reflect.setPrototypeOf(target, proto); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.setprototypeof](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.setprototypeof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.setPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Object.setPrototypeOf()`](../object/setprototypeof)
javascript Reflect.construct() Reflect.construct()
===================
The `Reflect.construct()` static method acts like the [`new`](../../operators/new) operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype.
Try it
------
Syntax
------
```
Reflect.construct(target, argumentsList)
Reflect.construct(target, argumentsList, newTarget)
```
### Parameters
`target` The target function to call.
`argumentsList` An array-like object specifying the arguments with which `target` should be called.
`newTarget` Optional
The constructor whose prototype should be used. See also the [`new.target`](../../operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`.
### Return value
A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`.
### Exceptions
A [`TypeError`](../typeerror), if `target` or `newTarget` are not constructors.
Description
-----------
`Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](../../operators/spread_syntax) combined with the [`new` operator](../../operators/new).)
```
const obj = new Foo(...args);
const obj = Reflect.construct(Foo, args);
```
### Reflect.construct() vs Object.create()
Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../object/create).
```
function OneClass() {
this.name = "one";
}
function OtherClass() {
this.name = "other";
}
// Calling this:
const obj1 = Reflect.construct(OneClass, args, OtherClass);
// ...has the same result as this:
const obj2 = Object.create(OtherClass.prototype);
OneClass.apply(obj2, args);
console.log(obj1.name); // 'one'
console.log(obj2.name); // 'one'
console.log(obj1 instanceof OneClass); // false
console.log(obj2 instanceof OneClass); // false
console.log(obj1 instanceof OtherClass); // true
console.log(obj2 instanceof OtherClass); // true
// Another example to demonstrate below:
function func1(a, b, c, d) {
console.log(arguments[3]);
}
function func2(d, e, f, g) {
console.log(arguments[3]);
}
const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]);
```
However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../function/apply), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object.
When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not.
```
function OneClass() {
console.log("OneClass");
console.log(new.target);
}
function OtherClass() {
console.log("OtherClass");
console.log(new.target);
}
const obj1 = Reflect.construct(OneClass, args);
// Logs:
// OneClass
// function OneClass { ... }
const obj2 = Reflect.construct(OneClass, args, OtherClass);
// Logs:
// OneClass
// function OtherClass { ... }
const obj3 = Object.create(OtherClass.prototype);
OneClass.apply(obj3, args);
// Logs:
// OneClass
// undefined
```
Examples
--------
### Using Reflect.construct()
```
const d = Reflect.construct(Date, [1776, 6, 4]);
d instanceof Date; // true
d.getFullYear(); // 1776
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.construct](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.construct) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.construct` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`new`](../../operators/new)
* [`new.target`](../../operators/new.target)
| programming_docs |
javascript Reflect.preventExtensions() Reflect.preventExtensions()
===========================
The `Reflect.preventExtensions()` static method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../object/preventextensions), but with [some differences](#difference_with_object.preventextensions).
Try it
------
Syntax
------
```
Reflect.preventExtensions(target)
```
### Parameters
`target` The target object on which to prevent extensions.
### Return value
A [`Boolean`](../boolean) indicating whether or not the target was successfully set to prevent extensions.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Examples
--------
### Using Reflect.preventExtensions()
See also [`Object.preventExtensions()`](../object/preventextensions).
```
// Objects are extensible by default.
const empty = {};
Reflect.isExtensible(empty); // true
// ...but that can be changed.
Reflect.preventExtensions(empty);
Reflect.isExtensible(empty); // false
```
### Difference with Object.preventExtensions()
If the `target` argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). With [`Object.preventExtensions()`](../object/preventextensions), a non-object `target` will be returned as-is without any errors.
```
Reflect.preventExtensions(1);
// TypeError: 1 is not an object
Object.preventExtensions(1);
// 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.preventextensions](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.preventExtensions` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Object.isExtensible()`](../object/isextensible)
javascript Reflect.ownKeys() Reflect.ownKeys()
=================
The `Reflect.ownKeys()` static method returns an array of the `target` object's own property keys.
Try it
------
Syntax
------
```
Reflect.ownKeys(target)
```
### Parameters
`target` The target object from which to get the own keys.
### Return value
An [`Array`](../array) of the `target` object's own property keys.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `[Object.getOwnPropertyNames(target)](../object/getownpropertynames).concat([Object.getOwnPropertySymbols(target)](../object/getownpropertysymbols))`.
Examples
--------
### Using Reflect.ownKeys()
```
Reflect.ownKeys({z: 3, y: 2, x: 1}) // [ "z", "y", "x" ]
Reflect.ownKeys([]) // ["length"]
const sym = Symbol.for('comet');
const sym2 = Symbol.for('meteor');
const obj = {
[sym]: 0,
'str': 0,
'773': 0,
'0': 0,
[sym2]: 0,
'-1': 0,
'8': 0,
'second str': 0,
};
Reflect.ownKeys(obj)
// [ "0", "8", "773", "str", "-1", "second str", Symbol(comet), Symbol(meteor) ]
// Indexes in numeric order,
// strings in insertion order,
// symbols in insertion order
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.ownkeys](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.ownkeys) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.ownKeys` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Object.getOwnPropertyNames()`](../object/getownpropertynames)
javascript Reflect.isExtensible() Reflect.isExtensible()
======================
The `Reflect.isExtensible()` static method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../object/isextensible), but with [some differences](#difference_with_object.isextensible).
Try it
------
Syntax
------
```
Reflect.isExtensible(target)
```
### Parameters
`target` The target object which to check if it is extensible.
### Return value
A [`Boolean`](../boolean) indicating whether or not the target is extensible.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Examples
--------
### Using Reflect.isExtensible()
See also [`Object.isExtensible()`](../object/isextensible).
```
// New objects are extensible.
const empty = {};
Reflect.isExtensible(empty); // true
// ...but that can be changed.
Reflect.preventExtensions(empty);
Reflect.isExtensible(empty); // false
// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Reflect.isExtensible(sealed); // false
// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Reflect.isExtensible(frozen); // false
```
### Difference with Object.isExtensible()
If the `target` argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). With [`Object.isExtensible()`](../object/isextensible), a non-object `target` will return false without any errors.
```
Reflect.isExtensible(1);
// TypeError: 1 is not an object
Object.isExtensible(1);
// false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.isextensible](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.isExtensible` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Object.isExtensible()`](../object/isextensible)
javascript Reflect.getOwnPropertyDescriptor() Reflect.getOwnPropertyDescriptor()
==================================
The `Reflect.getOwnPropertyDescriptor()` static method is similar to [`Object.getOwnPropertyDescriptor()`](../object/getownpropertydescriptor). It returns a property descriptor of the given property if it exists on the object, [`undefined`](../undefined) otherwise.
Try it
------
Syntax
------
```
Reflect.getOwnPropertyDescriptor(target, propertyKey)
```
### Parameters
`target` The target object in which to look for the property.
`propertyKey` The name of the property to get an own property descriptor for.
### Return value
A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../undefined).
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../undefined) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../object/getownpropertydescriptor) is how non-object targets are handled.
Examples
--------
### Using Reflect.getOwnPropertyDescriptor()
```
Reflect.getOwnPropertyDescriptor({ x: "hello" }, "x");
// {value: "hello", writable: true, enumerable: true, configurable: true}
Reflect.getOwnPropertyDescriptor({ x: "hello" }, "y");
// undefined
Reflect.getOwnPropertyDescriptor([], "length");
// {value: 0, writable: true, enumerable: false, configurable: false}
```
### Difference to Object.getOwnPropertyDescriptor()
If the `target` argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). With [`Object.getOwnPropertyDescriptor`](../object/getownpropertydescriptor), a non-object first argument will be coerced to an object at first.
```
Reflect.getOwnPropertyDescriptor("foo", 0);
// TypeError: "foo" is not non-null object
Object.getOwnPropertyDescriptor("foo", 0);
// { value: "f", writable: false, enumerable: true, configurable: false }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.getownpropertydescriptor](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.getownpropertydescriptor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.getOwnPropertyDescriptor` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Object.getOwnPropertyDescriptor()`](../object/getownpropertydescriptor)
javascript Reflect.getPrototypeOf() Reflect.getPrototypeOf()
========================
The `Reflect.getPrototypeOf()` static method is almost the same method as [`Object.getPrototypeOf()`](../object/getprototypeof). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object.
Try it
------
Syntax
------
```
Reflect.getPrototypeOf(target)
```
### Parameters
`target` The target object of which to get the prototype.
### Return value
The prototype of the given object. If there are no inherited properties, [`null`](../../operators/null) is returned.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object.
Examples
--------
### Using Reflect.getPrototypeOf()
```
Reflect.getPrototypeOf({}); // Object.prototype
Reflect.getPrototypeOf(Object.prototype); // null
Reflect.getPrototypeOf(Object.create(null)); // null
```
### Compared to Object.getPrototypeOf()
```
// Same result for Objects
Object.getPrototypeOf({}); // Object.prototype
Reflect.getPrototypeOf({}); // Object.prototype
// Both throw in ES5 for non-Objects
Object.getPrototypeOf("foo"); // Throws TypeError
Reflect.getPrototypeOf("foo"); // Throws TypeError
// In ES2015 only Reflect throws, Object coerces non-Objects
Object.getPrototypeOf("foo"); // String.prototype
Reflect.getPrototypeOf("foo"); // Throws TypeError
// To mimic the Object ES2015 behavior you need to coerce
Reflect.getPrototypeOf(Object("foo")); // String.prototype
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.getprototypeof](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.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 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.getPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Object.getPrototypeOf()`](../object/getprototypeof)
javascript Reflect.defineProperty() Reflect.defineProperty()
========================
The `Reflect.defineProperty()` static method is like [`Object.defineProperty()`](../object/defineproperty) but returns a [`Boolean`](../boolean).
Try it
------
Syntax
------
```
Reflect.defineProperty(target, propertyKey, attributes)
```
### Parameters
`target` The target object on which to define the property.
`propertyKey` The name of the property to be defined or modified.
`attributes` The attributes for the property being defined or modified.
### Return value
A [`Boolean`](../boolean) indicating whether or not the property was successfully defined.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../object/defineproperty) which is similar.
**Note:** `Object.defineProperty` returns the object or throws a [`TypeError`](../typeerror) if the property has not been successfully defined. `Reflect.defineProperty`, however, returns a [`Boolean`](../boolean) indicating whether or not the property was successfully defined.
Examples
--------
### Using Reflect.defineProperty()
```
const obj = {};
Reflect.defineProperty(obj, "x", { value: 7 }); // true
console.log(obj.x); // 7
```
### Checking if property definition has been successful
With [`Object.defineProperty`](../object/defineproperty), which returns an object if successful, or throws a [`TypeError`](../typeerror) otherwise, you would use a [`try...catch`](../../statements/try...catch) block to catch any error that occurred while defining a property.
Because `Reflect.defineProperty` returns a Boolean success status, you can just use an [`if...else`](../../statements/if...else) block here:
```
if (Reflect.defineProperty(target, property, attributes)) {
// success
} else {
// failure
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.defineproperty](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.defineproperty) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.defineProperty` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`Object.defineProperty()`](../object/defineproperty)
javascript Reflect.set() Reflect.set()
=============
The `Reflect.set()` static method works like setting a property on an object.
Try it
------
Syntax
------
```
Reflect.set(target, propertyKey, value)
Reflect.set(target, propertyKey, value, receiver)
```
### Parameters
`target` The target object on which to set the property.
`propertyKey` The name of the property to set.
`value` The value to set.
`receiver` Optional
The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead.
### Return value
A [`Boolean`](../boolean) indicating whether or not setting the property was successful.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](../../operators/property_accessors) syntax as a function.
Examples
--------
### Using Reflect.set()
```
// Object
let obj = {};
Reflect.set(obj, "prop", "value"); // true
obj.prop; // "value"
// Array
let arr = ["duck", "duck", "duck"];
Reflect.set(arr, 2, "goose"); // true
arr[2]; // "goose"
// It can truncate an array.
Reflect.set(arr, "length", 1); // true
arr; // ["duck"]
// With just one argument, propertyKey and value are "undefined".
let obj = {};
Reflect.set(obj); // true
Reflect.getOwnPropertyDescriptor(obj, "undefined");
// { value: undefined, writable: true, enumerable: true, configurable: true }
```
### Different target and receiver
When the `target` and `receiver` are different, `Reflect.set` will use the property descriptor of `target` (to find the setter or determine if the property is writable), but set the property on `receiver`.
```
const target = {};
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is {}; receiver is { a: 2 }
const target = { a: 1 };
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is { a: 1 }; receiver is { a: 2 }
const target = {
set a(v) {
this.b = v;
},
};
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is { a: [Setter] }; receiver is { b: 2 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.set](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.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` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.set` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [Property accessors](../../operators/property_accessors)
javascript Reflect.deleteProperty() Reflect.deleteProperty()
========================
The `Reflect.deleteProperty()` static method allows to delete properties. It is like the [`delete` operator](../../operators/delete) as a function.
Try it
------
Syntax
------
```
Reflect.deleteProperty(target, propertyKey)
```
### Parameters
`target` The target object on which to delete the property.
`propertyKey` The name of the property to be deleted.
### Return value
A [`Boolean`](../boolean) indicating whether or not the property was successfully deleted.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a [`Boolean`](../boolean) indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](../../operators/delete).
Examples
--------
### Using Reflect.deleteProperty()
```
const obj = { x: 1, y: 2 };
Reflect.deleteProperty(obj, "x"); // true
console.log(obj); // { y: 2 }
const arr = [1, 2, 3, 4, 5];
Reflect.deleteProperty(arr, "3"); // true
console.log(arr); // [1, 2, 3, undefined, 5]
// Returns true if no such property exists
Reflect.deleteProperty({}, "foo"); // true
// Returns false if a property is unconfigurable
Reflect.deleteProperty(Object.freeze({ foo: 1 }), "foo"); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.deleteproperty](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.deleteproperty) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.deleteProperty` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [`delete` operator](../../operators/delete)
| programming_docs |
javascript Reflect.get() Reflect.get()
=============
The `Reflect.get()` static method works like getting a property from an object (`target[propertyKey]`) as a function.
Try it
------
Syntax
------
```
Reflect.get(target, propertyKey)
Reflect.get(target, propertyKey, receiver)
```
### Parameters
`target` The target object on which to get the property.
`propertyKey` The name of the property to get.
`receiver` Optional
The value of `this` provided for the call to `target` if a getter is encountered. When used with [`Proxy`](../proxy), it can be an object that inherits from `target`.
### Return value
The value of the property.
### Exceptions
A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object).
Description
-----------
The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](../../operators/property_accessors) syntax as a function.
Examples
--------
### Using `Reflect.get()`
```
// Object
let obj = { x: 1, y: 2 }
Reflect.get(obj, 'x') // 1
// Array
Reflect.get(['zero', 'one'], 1) // "one"
// Proxy with a get handler
let x = {p: 1};
let obj = new Proxy(x, {
get(t, k, r) {
return k + 'bar'
}
})
Reflect.get(obj, 'foo') // "foobar"
//Proxy with get handler and receiver
let x = {p: 1, foo: 2};
let y = {foo: 3};
let obj = new Proxy(x, {
get(t, prop, receiver) {
return receiver[prop] + 'bar'
}
})
Reflect.get(obj, 'foo', y) // "3bar"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect.get](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.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` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Reflect.get` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
* [`Reflect`](../reflect)
* [Property accessors](../../operators/property_accessors)
javascript RangeError() constructor RangeError() constructor
========================
The `RangeError()` constructor creates an error when a value is not in the set or range of allowed values.
Syntax
------
```
new RangeError()
new RangeError(message)
new RangeError(message, options)
new RangeError(message, fileName)
new RangeError(message, fileName, lineNumber)
RangeError()
RangeError(message)
RangeError(message, options)
RangeError(message, fileName)
RangeError(message, fileName, lineNumber)
```
**Note:** `RangeError()` can be called with or without [`new`](../../operators/new). Both create a new `RangeError` 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
--------
### 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-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 |
| `RangeError` | 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)
* [`Array`](../array)
* [`Number.prototype.toExponential()`](../number/toexponential)
* [`Number.prototype.toFixed()`](../number/tofixed)
* [`Number.prototype.toPrecision()`](../number/toprecision)
* [`String.prototype.normalize()`](../string/normalize)
javascript Atomics.load() Atomics.load()
==============
The `Atomics.load()` static method returns a value at a given position in the array.
Try it
------
Syntax
------
```
Atomics.load(typedArray, index)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to load from.
### Return value
The value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using `load`
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
Atomics.add(ta, 0, 12);
Atomics.load(ta, 0); // 12
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.load](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.load) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `load` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.store()`](store)
javascript Atomics.compareExchange() Atomics.compareExchange()
=========================
The `Atomics.compareExchange()` static method exchanges a given replacement value at a given position in the array, if a given expected value equals the old value. It returns the old value at that position whether it was equal to the expected value or not. This atomic operation guarantees that no other write happens until the modified value is written back.
Try it
------
Syntax
------
```
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to exchange a `value`.
`expectedValue` The value to check for equality.
`replacementValue` The number to exchange.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using compareExchange()
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 7;
Atomics.compareExchange(ta, 0, 7, 12); // returns 7, the old value
Atomics.load(ta, 0); // 12
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.compareexchange](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.compareexchange) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `compareExchange` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.exchange()`](exchange)
javascript Atomics.add() Atomics.add()
=============
The `Atomics.add()` static method adds a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.
Try it
------
Syntax
------
```
Atomics.add(typedArray, index, value)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to add a `value` to.
`value` The number to add.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using add()
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
Atomics.add(ta, 0, 12); // returns 0, the old value
Atomics.load(ta, 0); // 12
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.add](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.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` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.sub()`](sub)
javascript Atomics.isLockFree() Atomics.isLockFree()
====================
The `Atomics.isLockFree()` static method is used to determine whether the `Atomics` methods use locks or atomic hardware operations when applied to typed arrays with the given element byte size. It returns `false` if the given size is not one of the [BYTES\_PER\_ELEMENT](../typedarray/bytes_per_element) property of integer TypedArray types.
Try it
------
Syntax
------
```
Atomics.isLockFree(size)
```
### Parameters
`size` The size in bytes to check.
### Return value
A `true` or `false` value indicating whether the operation is lock free.
Examples
--------
### Using isLockFree
```
Atomics.isLockFree(1); // true
Atomics.isLockFree(2); // true
Atomics.isLockFree(3); // false
Atomics.isLockFree(4); // true
Atomics.isLockFree(5); // false
Atomics.isLockFree(6); // false
Atomics.isLockFree(7); // false
Atomics.isLockFree(8); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.islockfree](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.islockfree) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isLockFree` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
javascript Atomics.notify() Atomics.notify()
================
The `Atomics.notify()` static method notifies up some agents that are sleeping in the wait queue.
**Note:** This operation works with a shared [`Int32Array`](../int32array) only. It will return `0` on non-shared `ArrayBuffer` objects.
Syntax
------
```
Atomics.notify(typedArray, index, count)
```
### Parameters
`typedArray` A shared [`Int32Array`](../int32array).
`index` The position in the `typedArray` to wake up on.
`count` Optional
The number of sleeping agents to notify. Defaults to [`+Infinity`](../infinity).
### Return value
* Returns the number of woken up agents.
* Returns `0`, if a non-shared [`ArrayBuffer`](../arraybuffer) object is used.
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not a [`Int32Array`](../int32array).
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using `notify`
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.notify](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.notify) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `notify` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.wait()`](wait)
javascript Atomics.and() Atomics.and()
=============
The `Atomics.and()` static method computes a bitwise AND with a given value at a given position in the array, and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.
Try it
------
Syntax
------
```
Atomics.and(typedArray, index, value)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to compute the bitwise AND.
`value` The number to compute the bitwise AND with.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Description
-----------
The bitwise AND operation only yields 1, if both `a` and `b` are 1. The truth table for the AND operation is:
| `a` | `b` | `a & b` |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
For example, a bitwise AND of `5 & 1` results in `0001` which is 1 in decimal.
```
5 0101
1 0001
----
1 0001
```
Examples
--------
### Using and()
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 5;
Atomics.and(ta, 0, 1); // returns 5, the old value
Atomics.load(ta, 0); // 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.and](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.and) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `and` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.or()`](or)
* [`Atomics.xor()`](xor)
javascript Atomics.sub() Atomics.sub()
=============
The `Atomics.sub()` static method subtracts a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.
Try it
------
Syntax
------
```
Atomics.sub(typedArray, index, value)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to subtract a `value` from.
`value` The number to subtract.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using sub
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 48;
Atomics.sub(ta, 0, 12); // returns 48, the old value
Atomics.load(ta, 0); // 36
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.sub](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.sub) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sub` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.add()`](add)
javascript Atomics.waitAsync() Atomics.waitAsync()
===================
The `Atomics.waitAsync()` static method waits asynchronously on a shared memory location and returns a [`Promise`](../promise).
Unlike [`Atomics.wait()`](wait), `waitAsync` is non-blocking and usable on the main thread.
**Note:** This operation only works with a shared [`Int32Array`](../int32array) or [`BigInt64Array`](../bigint64array).
Syntax
------
```
Atomics.waitAsync(typedArray, index, value)
Atomics.waitAsync(typedArray, index, value, timeout)
```
### Parameters
`typedArray` A shared [`Int32Array`](../int32array) or [`BigInt64Array`](../bigint64array).
`index` The position in the `typedArray` to wait on.
`value` The expected value to test.
`timeout` Optional
Time to wait in milliseconds. [`Infinity`](../infinity), if no time is provided.
### Return value
An [`Object`](../object) with the following properties:
`async` A boolean indicating whether the `value` property is a [`Promise`](../promise) or not.
`value` If `async` is `false`, it will be a string which is either `"not-equal"` or `"timed-out"` (only when the `timeout` parameter is `0`). If `async` is `true`, it will be a [`Promise`](../promise) which is fulfilled with a string value, either `"ok"` or `"timed-out"`. The promise is never rejected.
Examples
--------
### Using waitAsync()
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. The `result.value` will be a promise.
```
const result = Atomics.waitAsync(int32, 0, 0, 1000);
// { async: true, value: Promise {<pending>} }
```
In the reading thread or in another thread, the memory location 0 is called and the promise can be resolved with `"ok"`.
```
Atomics.notify(int32, 0);
// { async: true, value: Promise {<fulfilled>: 'ok'} }
```
If it isn't resolving to `"ok"`, the value in the shared memory location wasn't the expected (the `value` would be `"not-equal"` instead of a promise) or the timeout was reached (the promise will resolve to `"time-out"`).
Specifications
--------------
| Specification |
| --- |
| [Atomics.waitAsync # atomics.waitasync](https://tc39.es/proposal-atomics-wait-async/#atomics.waitasync) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `waitAsync` | 87 | 87 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | 1.4 | 16.0.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.wait()`](wait)
* [`Atomics.notify()`](notify)
| programming_docs |
javascript Atomics.xor() Atomics.xor()
=============
The `Atomics.xor()` static method computes a bitwise XOR with a given value at a given position in the array, and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.
Try it
------
Syntax
------
```
Atomics.xor(typedArray, index, value)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to compute the bitwise XOR.
`value` The number to compute the bitwise XOR with.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Description
-----------
The bitwise XOR operation yields 1, if `a` and `b` are different. The truth table for the XOR operation is:
| `a` | `b` | `a ^ b` |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
For example, a bitwise XOR of `5 ^ 1` results in `0100` which is 4 in decimal.
```
5 0101
1 0001
----
4 0100
```
Examples
--------
### Using xor
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 5;
Atomics.xor(ta, 0, 1); // returns 5, the old value
Atomics.load(ta, 0); // 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.xor](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.xor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `xor` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.and()`](and)
* [`Atomics.or()`](or)
javascript Atomics.store() Atomics.store()
===============
The `Atomics.store()` static method stores a given value at the given position in the array and returns that value.
Try it
------
Syntax
------
```
Atomics.store(typedArray, index, value)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to store a `value` in.
`value` The number to store.
### Return value
The value that has been stored.
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using store()
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
Atomics.store(ta, 0, 12); // 12
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.store](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.store) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `store` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.load()`](load)
javascript Atomics.or() Atomics.or()
============
The `Atomics.or()` static method computes a bitwise OR with a given value at a given position in the array, and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.
Try it
------
Syntax
------
```
Atomics.or(typedArray, index, value)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to compute the bitwise OR.
`value` The number to compute the bitwise OR with.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Description
-----------
The bitwise OR operation yields 1, if either `a` or `b` are 1. The truth table for the OR operation is:
| `a` | `b` | `a | b` |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
For example, a bitwise OR of `5 | 1` results in `0101` which is 5 in decimal.
```
5 0101
1 0001
----
5 0101
```
Examples
--------
### Using or
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 2;
Atomics.or(ta, 0, 1); // returns 2, the old value
Atomics.load(ta, 0); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.or](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.or) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `or` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.and()`](and)
* [`Atomics.xor()`](xor)
javascript Atomics.wait() Atomics.wait()
==============
The `Atomics.wait()` static method verifies that a given position in an [`Int32Array`](../int32array) still contains a given value and if so sleeps, awaiting a wakeup or a timeout. It returns a string which is either `"ok"`, `"not-equal"`, or `"timed-out"`.
**Note:** This operation only works with a shared [`Int32Array`](../int32array) or [`BigInt64Array`](../bigint64array) and may not be allowed on the main thread. For a non-blocking, asynchronous version of this method, see [`Atomics.waitAsync()`](waitasync).
Syntax
------
```
Atomics.wait(typedArray, index, value)
Atomics.wait(typedArray, index, value, timeout)
```
### Parameters
`typedArray` A shared [`Int32Array`](../int32array) or [`BigInt64Array`](../bigint64array).
`index` The position in the `typedArray` to wait on.
`value` The expected value to test.
`timeout` Optional
Time to wait in milliseconds. [`Infinity`](../infinity), if no time is provided.
### Return value
A string which is either `"ok"`, `"not-equal"`, or `"timed-out"`.
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not a shared [`Int32Array`](../int32array).
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using wait()
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.wait](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.wait) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `wait` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.waitAsync()`](waitasync)
* [`Atomics.notify()`](notify)
javascript Atomics.exchange() Atomics.exchange()
==================
The `Atomics.exchange()` static method stores a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens between the read of the old value and the write of the new value.
Try it
------
Syntax
------
```
Atomics.exchange(typedArray, index, value)
```
### Parameters
`typedArray` An integer typed array. One of [`Int8Array`](../int8array), [`Uint8Array`](../uint8array), [`Int16Array`](../int16array), [`Uint16Array`](../uint16array), [`Int32Array`](../int32array), [`Uint32Array`](../uint32array), [`BigInt64Array`](../bigint64array), or [`BigUint64Array`](../biguint64array).
`index` The position in the `typedArray` to exchange a `value`.
`value` The number to exchange.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
* Throws a [`TypeError`](../typeerror), if `typedArray` is not one of the allowed integer types.
* Throws a [`RangeError`](../rangeerror), if `index` is out of bounds in the `typedArray`.
Examples
--------
### Using exchange()
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
Atomics.exchange(ta, 0, 12); // returns 0, the old value
Atomics.load(ta, 0); // 12
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics.exchange](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics.exchange) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `exchange` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](../atomics)
* [`Atomics.compareExchange()`](compareexchange)
javascript Float64Array() constructor Float64Array() constructor
==========================
The `Float64Array()` typed array constructor creates a new [`Float64Array`](../float64array) object, which is, 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).
Syntax
------
```
new Float64Array()
new Float64Array(length)
new Float64Array(typedArray)
new Float64Array(object)
new Float64Array(buffer)
new Float64Array(buffer, byteOffset)
new Float64Array(buffer, byteOffset, length)
```
**Note:** `Float64Array()` 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 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 # 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 |
| `Float64Array` | 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 `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 Symbol.hasInstance Symbol.hasInstance
==================
The `Symbol.hasInstance` well-known symbol is used to determine if a constructor object recognizes an object as its instance. The [`instanceof`](../../operators/instanceof) operator's behavior can be customized by this symbol.
Try it
------
Value
-----
The well-known symbol `@@hasInstance`.
| Property attributes of `Symbol.hasInstance` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Examples
--------
### Custom instanceof behavior
You could implement your custom `instanceof` behavior like this, for example:
```
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true
```
```
function MyArray() {}
Object.defineProperty(MyArray, Symbol.hasInstance, {
value(instance) {
return Array.isArray(instance);
},
});
console.log([] instanceof MyArray); // true
```
### Checking the instance of an object
Just in the same manner at which you can check if an object is an instance of a class using the `instanceof` keyword, we can also use `Symbol.hasInstance` for such checks also.
```
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.hasinstance](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.hasinstance) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `hasInstance` | 50 | 15 | 50 | No | 37 | 10 | 50 | 50 | 50 | 37 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* [`instanceof`](../../operators/instanceof)
javascript Symbol.keyFor() Symbol.keyFor()
===============
The `Symbol.keyFor()` static method retrieves a shared symbol key from the global symbol registry for the given symbol.
Try it
------
Syntax
------
```
Symbol.keyFor(sym)
```
### Parameters
`sym` Symbol, required. The symbol to find a key for.
### Return value
A string representing the key for the given symbol if one is found on the [global registry](../symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../undefined).
Examples
--------
### Using keyFor()
```
const globalSym = Symbol.for("foo"); // create a new global symbol
Symbol.keyFor(globalSym); // "foo"
const localSym = Symbol();
Symbol.keyFor(localSym); // undefined
// well-known symbols are not symbols registered
// in the global symbol registry
Symbol.keyFor(Symbol.iterator); // undefined
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.keyfor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.keyfor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `keyFor` | 40 | 12 | 36 | No | 27 | 9 | 40 | 40 | 36 | 27 | 9 | 4.0 | 1.0 | 0.12.0 |
See also
--------
* [`Symbol.for()`](for)
javascript Symbol.asyncIterator Symbol.asyncIterator
====================
The `Symbol.asyncIterator` well-known symbol specifies the default [async iterator](../../iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](../../statements/for-await...of) loop.
Try it
------
Value
-----
The well-known symbol `@@asyncIterator`.
| Property attributes of `Symbol.asyncIterator` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `@@asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key.
Examples
--------
### User-defined async iterables
You can define your own async iterable by setting the `[Symbol.asyncIterator]` property on an object.
```
const myAsyncIterable = {
async \*[Symbol.asyncIterator]() {
yield "hello";
yield "async";
yield "iteration!";
},
};
(async () => {
for await (const x of myAsyncIterable) {
console.log(x);
}
})();
// Logs:
// "hello"
// "async"
// "iteration!"
```
When creating an API, remember that async iterables are designed to represent something *iterable* β like a stream of data or a list β, not to completely replace callbacks and events in most situations.
### Built-in async iterables
There are currently no built-in JavaScript objects that have the `[Symbol.asyncIterator]` key set by default. However, WHATWG Streams are set to be the first built-in object to be async iterable, with `[Symbol.asyncIterator]` recently landing in the spec.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.asynciterator](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.asynciterator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `asyncIterator` | 63 | 79 | 57 | No | 50 | 11.1 | 63 | 63 | 57 | 46 | 11.3 | 8.0 | 1.0 | 10.0.0 |
See also
--------
* [Iteration protocols](../../iteration_protocols)
* [for await...of](../../statements/for-await...of)
| programming_docs |
javascript Symbol.prototype[@@toPrimitive] Symbol.prototype[@@toPrimitive]
===============================
The `[@@toPrimitive]()` method converts a Symbol object to a primitive value.
Syntax
------
```
Symbol()[Symbol.toPrimitive](hint)
```
### Return value
The primitive value of the specified [`Symbol`](../symbol) object.
Description
-----------
The `[@@toPrimitive]()` method of [`Symbol`](../symbol) returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used.
JavaScript calls the `[@@toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[@@toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
Examples
--------
### Using @@toPrimitive
```
const sym = Symbol("example");
sym === sym[Symbol.toPrimitive](); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.prototype-@@toprimitive](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.prototype-@@toprimitive) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 |
See also
--------
* [`Symbol.toPrimitive`](toprimitive)
javascript Symbol.toPrimitive Symbol.toPrimitive
==================
The `Symbol.toPrimitive` well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion) algorithms.
Try it
------
Value
-----
The well-known symbol `@@toPrimitive`.
| Property attributes of `Symbol.toPrimitive` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`.
The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](../string#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[@@toPrimitive]()`](@@toprimitive) does). The language does not enforce alignment between the `hint` and the result type, although `[@@toPrimitive]()` must return a primitive, or a [`TypeError`](../typeerror) is thrown.
Objects without the `@@toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion) section. `@@toPrimitive` allows full control over the primitive conversion process. For example, [`Date.prototype[@@toPrimitive]`](../date/@@toprimitive) treats `"default"` as if it's `"string"` and calls `toString()` instead of `valueOf()`. [`Symbol.prototype[@@toPrimitive]`](@@toprimitive) ignores the hint and always returns a symbol, which means even in string contexts, [`Symbol.prototype.toString()`](tostring) won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../string/string).
Examples
--------
### Modifying primitive values converted from an object
Following example describes how `Symbol.toPrimitive` property can modify the primitive value converted from an object.
```
// An object without Symbol.toPrimitive property.
const obj1 = {};
console.log(+obj1); // NaN
console.log(`${obj1}`); // "[object Object]"
console.log(obj1 + ""); // "[object Object]"
// An object with Symbol.toPrimitive property.
const obj2 = {
[Symbol.toPrimitive](hint) {
if (hint === "number") {
return 10;
}
if (hint === "string") {
return "hello";
}
return true;
},
};
console.log(+obj2); // 10 β hint is "number"
console.log(`${obj2}`); // "hello" β hint is "string"
console.log(obj2 + ""); // "true" β hint is "default"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.toprimitive](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.toprimitive) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 |
See also
--------
* [`Date.prototype[@@toPrimitive]()`](../date/@@toprimitive)
* [`Symbol.prototype[@@toPrimitive]()`](@@toprimitive)
* [`Object.prototype.toString()`](../object/tostring)
* [`Object.prototype.valueOf()`](../object/valueof)
javascript Symbol.toStringTag Symbol.toStringTag
==================
The `Symbol.toStringTag` well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../object/tostring) method.
Try it
------
Value
-----
The well-known symbol `@@toStringTag`.
| Property attributes of `Symbol.toStringTag` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Examples
--------
### Default tags
Some values do not have `Symbol.toStringTag`, but have special `toString()` representations. For a complete list, see [`Object.prototype.toString()`](../object/tostring).
```
Object.prototype.toString.call('foo'); // "[object String]"
Object.prototype.toString.call([1, 2]); // "[object Array]"
Object.prototype.toString.call(3); // "[object Number]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
// ... and more
```
### Built-in toStringTag symbols
Most built-in objects provide their own `@@toStringTag` property. All built-in objects' `@@toStringTag` property is not writable, not enumerable, and configurable.
```
Object.prototype.toString.call(new Map()); // "[object Map]"
Object.prototype.toString.call(function\* () {}); // "[object GeneratorFunction]"
Object.prototype.toString.call(Promise.resolve()); // "[object Promise]"
// ... and more
```
### Custom tag with toStringTag
When creating your own class, JavaScript defaults to the "Object" tag:
```
class ValidatorClass {}
Object.prototype.toString.call(new ValidatorClass()); // "[object Object]"
```
Now, with the help of `toStringTag`, you are able to set your own custom tag:
```
class ValidatorClass {
get [Symbol.toStringTag]() {
return 'Validator';
}
}
Object.prototype.toString.call(new ValidatorClass()); // "[object Validator]"
```
### toStringTag available on all DOM prototype objects
Due to a [WebIDL spec change](https://github.com/whatwg/webidl/pull/357) in mid-2020, browsers are adding a `Symbol.toStringTag` property to all DOM prototype objects. For example, to access the `Symbol.toStringTag` property on [`HTMLButtonElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement):
```
const test = document.createElement('button');
test.toString(); // Returns [object HTMLButtonElement]
test[Symbol.toStringTag]; // Returns HTMLButtonElement
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.tostringtag](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.tostringtag) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 49 | 15 | 51 | No | 36 | 10 | 49 | 49 | 51 | 36 | 10 | 5.0 | 1.0 | 6.0.0
4.0.0 |
| `dom_objects` | 50 | 79 | 78 | No | 37 | 14 | 50 | 50 | 79 | 37 | 14 | 5.0 | 1.0 | No |
See also
--------
* [Polyfill of `Symbol.toStringTag` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Object.prototype.toString()`](../object/tostring)
javascript Symbol.matchAll Symbol.matchAll
===============
The `Symbol.matchAll` well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../string/matchall) method.
For more information, see [`RegExp.prototype[@@matchAll]()`](../regexp/@@matchall) and [`String.prototype.matchAll()`](../string/matchall).
Try it
------
Value
-----
The well-known symbol `@@matchAll`.
| Property attributes of `Symbol.matchAll` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Examples
--------
### Using Symbol.matchAll
```
const str = "2016-01-02|2019-03-07";
const numbers = {
\*[Symbol.matchAll](str) {
for (const n of str.matchAll(/[0-9]+/g)) yield n[0];
},
};
console.log(Array.from(str.matchAll(numbers)));
// ["2016", "01", "02", "2019", "03", "07"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.matchall](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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 | 11.0 | 1.0 | 12.0.0 |
See also
--------
* [Polyfill of `Symbol.matchAll` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`String.prototype.matchAll()`](../string/matchall)
* [`RegExp.prototype[@@matchAll]()`](../regexp/@@matchall)
javascript Symbol.split Symbol.split
============
The `Symbol.split` well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../string/split) method.
For more information, see [`RegExp.prototype[@@split]()`](../regexp/@@split) and [`String.prototype.split()`](../string/split).
Try it
------
Value
-----
The well-known symbol `@@split`.
| Property attributes of `Symbol.split` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Examples
--------
### Custom reverse split
```
class ReverseSplit {
[Symbol.split](string) {
const array = string.split(" ");
return array.reverse();
}
}
console.log("Another one bites the dust".split(new ReverseSplit()));
// [ "dust", "the", "bites", "one", "Another" ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.split](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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 `Symbol.split` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Symbol.match`](match)
* [`Symbol.replace`](replace)
* [`Symbol.search`](search)
* [`RegExp.prototype[@@split]()`](../regexp/@@split)
javascript Symbol.prototype.valueOf() Symbol.prototype.valueOf()
==========================
The `valueOf()` method returns the primitive value of a Symbol object.
Try it
------
Syntax
------
```
valueOf()
```
### Return value
The primitive value of the specified [`Symbol`](../symbol) object.
Description
-----------
The `valueOf()` method of [`Symbol`](../symbol) returns the primitive value of a Symbol object as a Symbol data type.
JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
Examples
--------
### Using valueOf()
```
const sym = Symbol("example");
sym === sym.valueOf(); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.prototype.valueof](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Object.prototype.valueOf()`](../object/valueof)
javascript Symbol.replace Symbol.replace
==============
The `Symbol.replace` well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../string/replace) method.
For more information, see [`RegExp.prototype[@@replace]()`](../regexp/@@replace) and [`String.prototype.replace()`](../string/replace).
Try it
------
Value
-----
The well-known symbol `@@replace`.
| Property attributes of `Symbol.replace` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Examples
--------
### Using Symbol.replace
```
class CustomReplacer {
constructor(value) {
this.value = value;
}
[Symbol.replace](string) {
return string.replace(this.value, "#!@?");
}
}
console.log("football".replace(new CustomReplacer("foo"))); // "#!@?tball"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.replace](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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 `Symbol.replace` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Symbol.match`](match)
* [`Symbol.search`](search)
* [`Symbol.split`](split)
* [`RegExp.prototype[@@replace]()`](../regexp/@@replace)
javascript Symbol.prototype.description Symbol.prototype.description
============================
The read-only `description` property is a string returning the optional description of [`Symbol`](../symbol) objects.
Try it
------
Description
-----------
[`Symbol`](../symbol) objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples.
Examples
--------
### Using description
```
Symbol("desc").toString(); // "Symbol(desc)"
Symbol("desc").description; // "desc"
Symbol("").description; // ""
Symbol().description; // undefined
// well-known symbols
Symbol.iterator.toString(); // "Symbol(Symbol.iterator)"
Symbol.iterator.description; // "Symbol.iterator"
// global symbols
Symbol.for("foo").toString(); // "Symbol(foo)"
Symbol.for("foo").description; // "foo"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.prototype.description](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.prototype.description) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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 |
See also
--------
* [Polyfill of `Symbol.prototype.description` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Symbol.prototype.toString()`](tostring)
* Polyfill: <https://npmjs.com/symbol.prototype.description>
javascript Symbol.iterator Symbol.iterator
===============
The well-known `Symbol.iterator` symbol specifies the default iterator for an object. Used by [`for...of`](../../statements/for...of).
Try it
------
Value
-----
The well-known symbol `@@iterator`.
| Property attributes of `Symbol.iterator` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `@@iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated.
Some built-in types have a default iteration behavior, while other types (such as [`Object`](../object)) do not. The built-in types with a `@@iterator` method are:
* [`Array.prototype[@@iterator]()`](../array/@@iterator)
* [`TypedArray.prototype[@@iterator]()`](../typedarray/@@iterator)
* [`String.prototype[@@iterator]()`](../string/@@iterator)
* [`Map.prototype[@@iterator]()`](../map/@@iterator)
* [`Set.prototype[@@iterator]()`](../set/@@iterator)
See also [Iteration protocols](../../iteration_protocols) for more information.
Examples
--------
### User-defined iterables
We can make our own iterables like this:
```
const myIterable = {};
myIterable[Symbol.iterator] = function\* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable]; // [1, 2, 3]
```
Or iterables can be defined directly inside a class or object using a [computed property](../../operators/object_initializer#computed_property_names):
```
class Foo {
\*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
}
const someObj = {
\*[Symbol.iterator]() {
yield "a";
yield "b";
},
};
console.log(...new Foo()); // 1, 2, 3
console.log(...someObj); // 'a', 'b'
```
### Non-well-formed iterables
If an iterable's `@@iterator` method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior:
```
const nonWellFormedIterable = {};
nonWellFormedIterable[Symbol.iterator] = () => 1;
[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.iterator](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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` | 43 | 12 | 36 | No | 30 | 10 | 43 | 43 | 36 | 30 | 10 | 4.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Symbol.iterator` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [Iteration protocols](../../iteration_protocols)
* [`Array.prototype[@@iterator]()`](../array/@@iterator)
* [`TypedArray.prototype[@@iterator]()`](../typedarray/@@iterator)
* [`String.prototype[@@iterator]()`](../string/@@iterator)
* [`Map.prototype[@@iterator]()`](../map/@@iterator)
* [`Set.prototype[@@iterator]()`](../set/@@iterator)
| programming_docs |
javascript Symbol.match Symbol.match
============
The `Symbol.match` well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../string/match) method.
For more information, see [`RegExp.prototype[@@match]()`](../regexp/@@match) and [`String.prototype.match()`](../string/match).
Try it
------
Value
-----
The well-known symbol `@@match`.
| Property attributes of `Symbol.match` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
This function is also used to identify [if objects have the behavior of regular expressions](../regexp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../string/startswith), [`String.prototype.endsWith()`](../string/endswith) and [`String.prototype.includes()`](../string/includes), check if their first argument is a regular expression and will throw a [`TypeError`](../typeerror) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object.
Examples
--------
### Marking a RegExp as not a regex
The following code will throw a [`TypeError`](../typeerror):
```
"/bar/".startsWith(/bar/);
// Throws TypeError, as /bar/ is a regular expression
// and Symbol.match is not modified.
```
However, if you set `Symbol.match` to `false`, the object will be considered as [not a regular expression object](../regexp#special_handling_for_regexes). The methods `startsWith` and `endsWith` won't throw a `TypeError` as a consequence.
```
const re = /foo/;
re[Symbol.match] = false;
"/foo/".startsWith(re); // true
"/baz/".endsWith(re); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.match](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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 | 79 | 40 | No | 37 | 10 | 50 | 50 | 40 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Symbol.match` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Symbol.replace`](replace)
* [`Symbol.search`](search)
* [`Symbol.split`](split)
* [`RegExp.prototype[@@match]()`](../regexp/@@match)
javascript Symbol() constructor Symbol() constructor
====================
The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](../../classes/extends) clause of a `class` definition but a [`super`](../../operators/super) call to it will cause an exception.
Try it
------
Syntax
------
```
Symbol()
Symbol(description)
```
**Note:** `Symbol()` can only be called without [`new`](../../operators/new). Attempting to construct it with `new` throws a [`TypeError`](../typeerror).
### Parameters
`description` Optional
A string. A description of the symbol which can be used for debugging but not to access the symbol itself.
Examples
--------
### Creating symbols
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
```
### new Symbol()
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");
const symObj = Object(sym);
typeof sym; // "symbol"
typeof symObj; // "object"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol-constructor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol-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 |
| `Symbol` | 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)
javascript Symbol.isConcatSpreadable Symbol.isConcatSpreadable
=========================
The `Symbol.isConcatSpreadable` well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../array/concat) method.
Try it
------
Value
-----
The well-known symbol `@@isConcatSpreadable`.
| Property attributes of `Symbol.isConcatSpreadable` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
The `@@isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects:
* For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases.
* For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases.
Examples
--------
### Arrays
By default, [`Array.prototype.concat()`](../array/concat) spreads (flattens) arrays into its result:
```
const alpha = ["a", "b", "c"];
const numeric = [1, 2, 3];
const alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]
```
When setting `Symbol.isConcatSpreadable` to `false`, you can disable the default behavior:
```
const alpha = ["a", "b", "c"];
const numeric = [1, 2, 3];
numeric[Symbol.isConcatSpreadable] = false;
const alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // Result: ['a', 'b', 'c', [1, 2, 3] ]
```
### Array-like objects
For array-like objects, the default is to not spread. `Symbol.isConcatSpreadable` needs to be set to `true` in order to get a flattened array:
```
const x = [1, 2, 3];
const fakeArray = {
[Symbol.isConcatSpreadable]: true,
length: 2,
0: "hello",
1: "world",
};
x.concat(fakeArray); // [1, 2, 3, "hello", "world"]
```
**Note:** The `length` property is used to control the number of object properties to be added. In the above example, `length:2` indicates two properties has to be added.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.isconcatspreadable](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.isconcatspreadable) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isConcatSpreadable` | 48 | 15 | 48 | No | 35 | 10 | 48 | 48 | 48 | 35 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Symbol.isConcatSpreadable` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Array.prototype.concat()`](../array/concat)
javascript Symbol.unscopables Symbol.unscopables
==================
The `Symbol.unscopables` well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](../../statements/with) environment bindings of the associated object.
Try it
------
Value
-----
The well-known symbol `@@unscopables`.
| Property attributes of `Symbol.unscopables` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](../../statements/with) environment bindings. Note that when using [strict mode](../../strict_mode), `with` statements are not available, and this symbol is likely not needed.
Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object *unscopable* and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value) will make it *scopable* and thus appear as lexical scope variables.
When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../object/tostring) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example below](#avoid_using_a_non-null-prototype_object_as_unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[@@unscopables]`](../array/@@unscopables) does.
This protocol is also utilized by DOM APIs, such as [`Element.prototype.append()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/append).
Examples
--------
### Scoping in with statements
The following code works fine in ES5 and below. However, in ECMAScript 2015 and later, the [`Array.prototype.keys()`](../array/keys) method was introduced. That means that inside a `with` environment, "keys" would now be the method and not the variable. That's why the `@@unscopables` symbol was introduced. A built-in `@@unscopables` setting is implemented as [`Array.prototype[@@unscopables]`](../array/@@unscopables) to prevent some of the Array methods being scoped into the `with` statement.
```
var keys = [];
with (Array.prototype) {
keys.push("something");
}
```
### Unscopables in objects
You can also set `@@unscopables` for your own objects.
```
const obj = {
foo: 1,
bar: 2,
baz: 3,
};
obj[Symbol.unscopables] = {
// Make the object have `null` prototype to prevent
// `Object.prototype` methods from being unscopable
\_\_proto\_\_: null,
// `foo` will be scopable
foo: false,
// `bar` will be unscopable
bar: true,
// `baz` is omitted; because `undefined` is falsy, it is also scopable (default)
};
with (obj) {
console.log(foo); // 1
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // 3
}
```
### Avoid using a non-null-prototype object as @@unscopables
Declaring `@@unscopables` as a plain object without eliminating its prototype may cause subtle bugs. Consider the following code working before `@@unscopables`:
```
const character = {
name: "Yoda",
toString: function () {
return "Use with statements, you must not";
},
};
with (character) {
console.log(name + ' says: "' + toString() + '"'); // Yoda says: "Use with statements, you must not"
}
```
To preserve backward compatibility, you decided to add an `@@unscopables` property when adding more properties to `character`. You may naΓ―vely do it like:
```
const character = {
name: "Yoda",
toString: function () {
return "Use with statements, you must not";
},
student: "Luke",
[Symbol.unscopables]: {
// Make `student` unscopable
student: true,
},
};
```
However, the code above now breaks:
```
with (character) {
console.log(name + ' says: "' + toString() + '"'); // Yoda says: "[object Undefined]"
}
```
This is because when looking up `character[Symbol.unscopables].toString`, it returns [`Object.prototype.toString()`](../object/tostring), which is a truthy value, thus making the `toString()` call in the `with()` statement reference `globalThis.toString()` instead β and because it's called without a [`this`](../../operators/this), `this` is `undefined`, making it return `[object Undefined]`.
Even when the method is not overridden by `character`, making it unscopable will change the value of `this`.
```
const proto = {};
const obj = { \_\_proto\_\_: proto };
with (proto) {
console.log(isPrototypeOf(obj)); // true; `isPrototypeOf` is scoped and `this` is `proto`
}
proto[Symbol.unscopables] = {};
with (proto) {
console.log(isPrototypeOf(obj)); // TypeError: Cannot convert undefined or null to object
// `isPrototypeOf` is unscoped and `this` is undefined
}
```
To fix this, always make sure `@@unscopables` only contains properties you wish to be unscopable, without `Object.prototype` properties.
```
const character = {
name: "Yoda",
toString: function () {
return "Use with statements, you must not";
},
student: "Luke",
[Symbol.unscopables]: {
// Make the object have `null` prototype to prevent
// `Object.prototype` methods from being unscopable
\_\_proto\_\_: null,
// Make `student` unscopable
student: true,
},
};
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.unscopables](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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 | 9 | 38 | 38 | 48 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Array.prototype[@@unscopables]`](../array/@@unscopables)
* [`with`](../../statements/with) statement (not available in [Strict mode](../../strict_mode))
* [`Element.prototype.append()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/append)
javascript Symbol.search Symbol.search
=============
The `Symbol.search` well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../string/search) method.
For more information, see [`RegExp.prototype[@@search]()`](../regexp/@@search) and [`String.prototype.search()`](../string/search).
Try it
------
Value
-----
The well-known symbol `@@search`.
| Property attributes of `Symbol.search` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Examples
--------
### Custom string search
```
class caseInsensitiveSearch {
constructor(value) {
this.value = value.toLowerCase();
}
[Symbol.search](string) {
return string.toLowerCase().indexOf(this.value);
}
}
console.log("foobar".search(new caseInsensitiveSearch("BaR"))); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.search](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `Symbol.search` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Symbol.match`](match)
* [`Symbol.replace`](replace)
* [`Symbol.split`](split)
* [`RegExp.prototype[@@search]()`](../regexp/@@search)
javascript Symbol.prototype.toString() Symbol.prototype.toString()
===========================
The `toString()` method returns a string representing the specified symbol value.
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the specified symbol value.
Description
-----------
The [`Symbol`](../symbol) object overrides the `toString` method of [`Object`](../object); it does not inherit [`Object.prototype.toString()`](../object/tostring). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's <description>.
The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../typeerror) for other `this` values without attempting to coerce them to symbol values.
Because `Symbol` has a [`[@@toPrimitive]()`](@@toprimitive) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](../string#string_coercion). However, because `Symbol.prototype[@@toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../typeerror) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](../string/string#using_string_to_stringify_a_symbol) function.
Examples
--------
### Using toString()
```
Symbol("desc").toString(); // "Symbol(desc)"
// well-known symbols
Symbol.iterator.toString(); // "Symbol(Symbol.iterator)"
// global symbols
Symbol.for("foo").toString(); // "Symbol(foo)"
```
### Implicitly calling toString()
The only way to make JavaScript implicitly call `toString()` instead of [`[@@toPrimitive]()`](@@toprimitive) on a symbol wrapper object is by [deleting](../../operators/delete) the `@@toPrimitive` method first.
**Warning:** You should not do this in practice. Never mutate built-in objects unless you know exactly what you're doing.
```
delete Symbol.prototype[Symbol.toPrimitive];
console.log(`${Object(Symbol("foo"))}`); // "Symbol(foo)"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.prototype.tostring](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Object.prototype.toString()`](../object/tostring)
javascript Symbol.species Symbol.species
==============
The well-known symbol `Symbol.species` specifies a function-valued property that the constructor function uses to create derived objects.
**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
------
Value
-----
The well-known symbol `@@species`.
| Property attributes of `Symbol.species` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
The `@@species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`map()`](../array/map). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. For more information, see [subclassing built-ins](../../classes/extends#subclassing_built-ins).
All built-in implementations of `@@species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class β for example, `map()` will return an array of the same type as the original array.
Examples
--------
### Using species
You might want to return [`Array`](../array) objects in your derived array class `MyArray`. For example, when using methods such as [`map()`](../array/map) that return the default constructor, you want these methods to return a parent `Array` object, instead of the `MyArray` object. The `species` symbol lets you do this:
```
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
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.species](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.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 | 41 | No | 38 | 10 | 51 | 51 | 41 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* [`Array[@@species]`](../array/@@species)
* [`ArrayBuffer[@@species]`](../arraybuffer/@@species)
* [`Map[@@species]`](../map/@@species)
* [`Promise[@@species]`](../promise/@@species)
* [`RegExp[@@species]`](../regexp/@@species)
* [`Set[@@species]`](../set/@@species)
* [`TypedArray[@@species]`](../typedarray/@@species)
| programming_docs |
javascript Symbol.for() Symbol.for()
============
The `Symbol.for()` static method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.
Try it
------
Syntax
------
```
Symbol.for(key)
```
### Parameters
`key` String, required. The key for the symbol (and also used for the description of the symbol).
### Return value
An existing symbol with the given key if found; otherwise, a new symbol is created and returned.
Description
-----------
In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](../symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol.
Examples
--------
### Using Symbol.for()
```
Symbol.for("foo"); // create a new global symbol
Symbol.for("foo"); // retrieve the already created symbol
// Same global symbol, but not locally
Symbol.for("bar") === Symbol.for("bar"); // true
Symbol("bar") === Symbol("bar"); // false
// The key is also used as the description
const sym = Symbol.for("mario");
sym.toString(); // "Symbol(mario)"
```
To avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols:
```
Symbol.for("mdn.foo");
Symbol.for("mdn.bar");
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol.for](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol.for) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 40 | 12 | 36 | No | 27 | 9 | 40 | 40 | 36 | 27 | 9 | 4.0 | 1.0 | 0.12.0 |
See also
--------
* [`Symbol.keyFor()`](keyfor)
javascript Int32Array() constructor Int32Array() constructor
========================
The `Int32Array()` typed array constructor creates 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).
Syntax
------
```
new Int32Array()
new Int32Array(length)
new Int32Array(typedArray)
new Int32Array(object)
new Int32Array(buffer)
new Int32Array(buffer, byteOffset)
new Int32Array(buffer, byteOffset, length)
```
**Note:** `Int32Array()` 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 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 # 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 |
| `Int32Array` | 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 `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 Function.prototype.displayName Function.prototype.displayName
==============================
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The optional `displayName` property of a [`Function`](../function) instance specifies the display name of the function.
Value
-----
The `displayName` property is not initially present on any function β it's added by the code authors. For the purpose of display, it should be a string.
Description
-----------
The `displayName` property, if present, may be preferred by consoles and profilers over the [`name`](name) property to be displayed as the name of a function.
Among browsers, only the Firefox console utilizes this property. React devtools also use the [`displayName`](https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging) property when displaying the component tree.
Firefox does some basic attempts to decode the `displayName` that's possibly generated by the [anonymous JavaScript functions naming convention](http://johnjbarton.github.io/nonymous/index.html) algorithm. The following patterns are detected:
* If `displayName` ends with a sequence of alphanumeric characters, `_`, and `$`, the longest such suffix is displayed.
* If `displayName` ends with a sequence of `[]`-enclosed characters, that sequence is displayed without the square brackets.
* If `displayName` ends with a sequence of alphanumeric characters and `_` followed by some `/`, `.`, or `<`, the sequence is returned without the trailing `/`, `.`, or `<` characters.
* If `displayName` ends with a sequence of alphanumeric characters and `_` followed by `(^)`, the sequence is displayed without the `(^)`.
If none of the above patterns match, the entire `displayName` is displayed.
Examples
--------
### Setting a displayName
By entering the following in a Firefox console, it should display as something like `function MyFunction()`:
```
const a = function () {};
a.displayName = "MyFunction";
a; // function MyFunction()
```
### Changing displayName dynamically
You can dynamically change the `displayName` of a function:
```
const object = {
// anonymous
someMethod: function someMethod(value) {
someMethod.displayName = `someMethod (${value})`;
},
};
console.log(object.someMethod.displayName); // undefined
object.someMethod("123");
console.log(object.someMethod.displayName); // "someMethod (123)"
```
### Cleaning of displayName
Firefox devtools would clean up a few common patterns in the `displayName` property before displaying it.
```
function foo() {}
function testName(name) {
foo.displayName = name;
console.log(foo);
}
testName("$foo$"); // function $foo$()
testName("foo bar"); // function bar()
testName("Foo.prototype.add"); // function add()
testName("foo ."); // function foo .()
testName("foo <"); // function foo <()
testName("foo?"); // function foo?()
testName("foo()"); // function foo()()
testName("[...]"); // function ...()
testName("foo<"); // function foo()
testName("foo..."); // function foo()
testName("foo(^)"); // function foo()
```
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 |
| `displayName` | No | No | 13 | No | No | No | No | No | 14 | No | No | No | No | No |
See also
--------
* [`Function.prototype.name`](name)
javascript Function.prototype.prototype Function.prototype.prototype
============================
The `prototype` data property of a [`Function`](../function) instance is used when the function is used as a constructor with the [`new`](../../operators/new) operator. It will become the new object's prototype.
**Note:** Not all [`Function`](../function) objects have the `prototype` property β see [description](#description).
Value
-----
An object.
| Property attributes of `Function.prototype.prototype` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | no |
**Note:** The `prototype` property of [classes](../../classes) is not writable.
Description
-----------
When a function is called with [`new`](../../operators/new), the constructor's `prototype` property will become the resulting object's prototype.
```
function Ctor() {}
const inst = new Ctor();
console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true
```
You can read [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype.
A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](../../statements/function*) have a `prototype` property, but cannot be called with `new`:
```
async function\* asyncGeneratorFunction() {}
function\* generatorFunction() {}
```
Instead, generator functions' `prototype` property is used when they are called *without* `new`. The `prototype` property will become the returned [`Generator`](../generator) object's prototype.
In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../symbol/symbol) and [`BigInt()`](../bigint/bigint) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed.
The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned:
```
const method = { foo() {} }.foo;
const arrowFunction = () => {};
async function asyncFunction() {}
```
The following are valid constructors that have `prototype`:
```
class Class {}
function fn() {}
```
A [bound function](bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance.
```
const boundFunction = function () {}.bind(null);
```
A function's `prototype` property, by default, is a plain object with one property: [`constructor`](../object/constructor), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable.
If the `prototype` of a function is reassigned with something other than an [`Object`](../object), when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.)
```
function Ctor() {}
Ctor.prototype = 3;
console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true
```
Examples
--------
### Changing the prototype of all instances by mutating the prototype property
```
function Ctor() {}
const p1 = new Ctor();
const p2 = new Ctor();
Ctor.prototype.prop = 1;
console.log(p1.prop); // 1
console.log(p2.prop); // 1
```
### Adding a non-method property to a class's prototype property
[Class fields](../../classes/public_class_fields) add properties to each instance. Class methods declare *function* properties on the prototype. However, there's no way to add a non-function property to the prototype. In case you want to share static data between all instances (for example, [`Error.prototype.name`](../error/name) is the same between all error instances), you can manually assign it on the `prototype` of a class.
```
class Dog {
constructor(name) {
this.name = name;
}
}
Dog.prototype.species = "dog";
console.log(new Dog("Jack").species); // "dog"
```
This can be made more ergonomic using [static initialization blocks](../../classes/static_initialization_blocks), which are called when the class is initialized.
```
class Dog {
static {
Dog.prototype.species = "dog";
}
constructor(name) {
this.name = name;
}
}
console.log(new Dog("Jack").species); // "dog"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-instances-prototype](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function-instances-prototype) |
See also
--------
* [`Function`](../function)
* [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors)
javascript Function.prototype.bind() Function.prototype.bind()
=========================
The `bind()` method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Try it
------
Syntax
------
```
bind(thisArg)
bind(thisArg, arg1)
bind(thisArg, arg1, arg2)
bind(thisArg, arg1, arg2, /\* β¦, \*/ argN)
```
### Parameters
`thisArg` The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](../../strict_mode), [`null`](../../operators/null) and [`undefined`](../undefined) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the [`new`](../../operators/new) operator.
`arg1, β¦, argN` Optional
Arguments to prepend to arguments provided to the bound function when invoking `func`.
### Return value
A copy of the given function with the specified `this` value, and initial arguments (if provided).
Description
-----------
The `bind()` function creates a new *bound function*. Calling the bound function generally results in the execution of the function it wraps, which is also called the *target function*. The bound function will store the parameters passed β which include the value of `this` and the first few arguments β as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed).
A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`.
```
"use strict"; // prevent `this` from being boxed into the wrapper object
function log(...args) {
console.log(this, ...args);
}
const boundLog = log.bind("this value", 1, 2);
const boundLog2 = boundLog.bind("new this value", 3, 4);
boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6
```
A bound function may also be constructed using the [`new`](../../operators/new) operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../reflect/construct)). If the bound function is directly constructed, [`new.target`](../../operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.)
```
class Base {
constructor(...args) {
console.log(new.target === Base);
console.log(args);
}
}
const BoundBase = Base.bind(null, 1, 2);
new BoundBase(3, 4); // true, [1, 2, 3, 4]
```
However, because a bound function does not have the [`prototype`](prototype) property, it cannot be used as a base class for [`extends`](../../classes/extends).
```
class Derived extends class {}.bind(null) {}
// TypeError: Class extends value does not have valid prototype property undefined
```
When using a bound function as the right-hand side of [`instanceof`](../../operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead.
```
class Base {}
const BoundBase = Base.bind(null, 1, 2);
console.log(new Base() instanceof BoundBase); // true
```
The bound function has the following properties:
[`length`](length) The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value.
[`name`](name) The `name` of the target function plus a `"bound "` prefix.
The bound function also inherits the [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](../../classes/static) if the target function is a class).
Examples
--------
### Creating a bound function
The simplest use of `bind()` is to make a function that, no matter how it is called, is called with a particular `this` value.
A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its `this` (e.g., by using the method in callback-based code).
Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:
```
this.x = 9; // 'this' refers to the global object (e.g. 'window') in non-strict mode
const module = {
x: 81,
getX() {
return this.x;
},
};
console.log(module.getX()); // 81
const retrieveX = module.getX;
console.log(retrieveX()); // 9; the function gets invoked at the global scope
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global variable 'x' with module's property 'x'
const boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81
```
**Note:** If you run this example in [strict mode](../../strict_mode) (e.g. in ECMAScript modules, or through the `"use strict"` directive), the global `this` value will be undefined, causing the `retrieveX` call to fail.
If you run this in a Node CommonJS module, the top-scope `this` will be pointing to `module.exports` instead of `globalThis`, regardless of being in strict mode or not. However, in functions, the reference of unbound `this` still follows the rule of "`globalThis` in non-strict, `undefined` in strict". Therefore, in non-strict mode (default), `retrieveX` will return `undefined` because `this.x = 9` is writing to a different object (`module.exports`) from what `getX` is reading from (`globalThis`).
In fact, some built-in "methods" are also getters that return bound functions β one notable example being [`Intl.NumberFormat.prototype.format()`](../intl/numberformat/format#using_format_with_map), which, when accessed, returns a bound function that you can directly pass as a callback.
### Partially applied functions
The next simplest use of `bind()` is to make a function with pre-specified initial arguments.
These arguments (if any) follow the provided `this` value and are then inserted at the start of the arguments passed to the target function, followed by whatever arguments are passed to the bound function at the time it is called.
```
function list(...args) {
return args;
}
function addArguments(arg1, arg2) {
return arg1 + arg2;
}
console.log(list(1, 2, 3)); // [1, 2, 3]
console.log(addArguments(1, 2)); // 3
// Create a function with a preset leading argument
const leadingThirtySevenList = list.bind(null, 37);
// Create a function with a preset first argument.
const addThirtySeven = addArguments.bind(null, 37);
console.log(leadingThirtySevenList()); // [37]
console.log(leadingThirtySevenList(1, 2, 3)); // [37, 1, 2, 3]
console.log(addThirtySeven(5)); // 42
console.log(addThirtySeven(5, 10)); // 42
// (the second argument is ignored)
```
### With setTimeout()
By default, within [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout), the `this` keyword will be set to [`globalThis`](../globalthis), which is [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) in browsers. When working with class methods that require `this` to refer to class instances, you may explicitly bind `this` to the callback function, in order to maintain the instance.
```
class LateBloomer {
constructor() {
this.petalCount = Math.floor(Math.random() \* 12) + 1;
}
bloom() {
// Declare bloom after a delay of 1 second
setTimeout(this.declare.bind(this), 1000);
}
declare() {
console.log(`I am a beautiful flower with ${this.petalCount} petals!`);
}
}
const flower = new LateBloomer();
flower.bloom();
// After 1 second, calls 'flower.declare()'
```
You can also use [arrow functions](../../functions/arrow_functions) for this purpose.
```
class LateBloomer {
bloom() {
// Declare bloom after a delay of 1 second
setTimeout(() => this.declare(), 1000);
}
}
```
### Bound functions used as constructors
Bound functions are automatically suitable for use with the [`new`](../../operators/new) operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided `this` is ignored. However, provided arguments are still prepended to the constructor call.
```
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return `${this.x},${this.y}`;
};
const p = new Point(1, 2);
p.toString();
// '1,2'
// The thisArg's value doesn't matter because it's ignored
const YAxisPoint = Point.bind(null, 0 /\*x\*/);
const axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'
axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new YAxisPoint(17, 42) instanceof Point; // true
```
Note that you need not do anything special to create a bound function for use with [`new`](../../operators/new). [`new.target`](../../operators/new.target), [`instanceof`](../../operators/instanceof), [`this`](../../operators/this) etc. all work as expected, as if the constructor was never bound. The only difference is that it can no longer be used for [`extends`](../../classes/extends).
The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using [`new`](../../operators/new). If you call it without `new`, the bound `this` is suddenly not ignored.
```
const emptyObj = {};
const YAxisPoint = Point.bind(emptyObj, 0 /\*x\*/);
// Can still be called as a normal function
// (although usually this is undesirable)
YAxisPoint(13);
// The modifications to `this` is now observable from the outside
console.log(emptyObj); // { x: 0, y: 13 }
```
If you wish to restrict a bound function to only be callable with [`new`](../../operators/new), or only be callable without `new`, the target function must enforce that restriction, such as by checking `new.target !== undefined` or using a [class](../../classes) instead.
### Binding classes
Using `bind()` on classes preserves most of the class's semantics, except that all static own properties of the current class are lost. However, because the prototype chain is preserved, you can still access static properties inherited from the parent class.
```
class Base {
static baseProp = "base";
}
class Derived extends Base {
static derivedProp = "derived";
}
const BoundDerived = Derived.bind(null);
console.log(BoundDerived.baseProp); // "base"
console.log(BoundDerived.derivedProp); // undefined
console.log(new BoundDerived() instanceof Derived); // true
```
### Transforming methods to utility functions
`bind()` is also helpful in cases where you want to transform a method which requires a specific `this` value to a plain utility function that accepts the previous `this` parameter as a normal parameter. This is similar to how general-purpose utility functions work: instead of calling `array.map(callback)`, you use `map(array, callback)`, which avoids mutating `Array.prototype`, and allows you to use `map` with array-like objects that are not arrays (for example, [`arguments`](../../functions/arguments)).
Take [`Array.prototype.slice()`](../array/slice), for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:
```
const slice = Array.prototype.slice;
// ...
slice.call(arguments);
```
Note that you can't save `slice.call` and call it as a plain function, because the `call()` method also reads its `this` value, which is the function it should call. In this case, you can use `bind()` to bind the value of `this` for `call()`. In the following piece of code, `slice()` is a bound version of [`Function.prototype.call()`](call), with the `this` value bound to [`Array.prototype.slice()`](../array/slice). This means that additional `call()` calls can be eliminated:
```
// Same as "slice" in the previous example
const unboundSlice = Array.prototype.slice;
const slice = Function.prototype.call.bind(unboundSlice);
// ...
slice(arguments);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function.prototype.bind](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function.prototype.bind) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `bind` | 7 | 12 | 4 | 9 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 6 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Function.prototype.bind` in `core-js`](https://github.com/zloirock/core-js#ecmascript-function)
* [`Function.prototype.apply()`](apply)
* [`Function.prototype.call()`](call)
* [Functions](../../functions)
| programming_docs |
javascript Function.prototype.apply() Function.prototype.apply()
==========================
The `apply()` method calls the specified function with a given `this` value, and `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)).
Try it
------
Syntax
------
```
apply(thisArg)
apply(thisArg, argsArray)
```
### Parameters
`thisArg` The value of `this` provided for the call to `func`. If the function is not in [strict mode](../../strict_mode), [`null`](../../operators/null) and [`undefined`](../undefined) will be replaced with the global object, and primitive values will be converted to objects.
`argsArray` Optional
An array-like object, specifying the arguments with which `func` should be called, or [`null`](../../operators/null) or [`undefined`](../undefined) if no arguments should be provided to the function.
### Return value
The result of calling the function with the specified `this` value and arguments.
Description
-----------
**Note:** This function is almost identical to [`call()`](call), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** β for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`.
Normally, when calling a function, the value of [`this`](../../operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.
You can also use any kind of object which is array-like as the second parameter. In practice, this means that it needs to have a `length` property, and integer ("index") properties in the range `(0..length - 1)`. For example, you could use a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), or a custom object like `{ 'length': 2, '0': 'eat', '1': 'bananas' }`. You can also use [`arguments`](../../functions/arguments), for example:
```
function wrapper() {
return anotherFn.apply(null, arguments);
}
```
With the [rest parameters](../../functions/rest_parameters) and parameter [spread syntax](../../operators/spread_syntax), this can be rewritten as:
```
function wrapper(...args) {
return anotherFn(...args);
}
```
In general, `fn.apply(null, args)` is equivalent to `fn(...args)` with the parameter spread syntax, except `args` is expected to be an array-like object in the former case with `apply()`, and an [iterable](../../iteration_protocols#the_iterable_protocol) object in the latter case with spread syntax.
**Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](../../operators/new.target) is `undefined`, and classes throw an error because they can't be called without [`new`](../../operators/new). Use [`Reflect.construct()`](../reflect/construct) or [`extends`](../../classes/extends) instead.
Examples
--------
### Using apply() to append an array to another
You can use [`Array.prototype.push()`](../array/push) to append an element to an array. Because `push()` accepts a variable number of arguments, you can also push multiple elements at once. But if you pass an array to `push()`, it will actually add that array as a single element, instead of adding the elements individually, ending up with an array inside an array. On the other hand, [`Array.prototype.concat()`](../array/concat) does have the desired behavior in this case, but it does not append to the *existing* array β it creates and returns a new array.
In this case, you can use `apply` to implicitly "spread" an array as a series of arguments.
```
const array = ["a", "b"];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
```
The same effect can be achieved with the spread syntax.
```
const array = ["a", "b"];
const elements = [0, 1, 2];
array.push(...elements);
console.info(array); // ["a", "b", 0, 1, 2]
```
### Using apply() and built-in functions
Clever usage of `apply()` allows you to use built-in functions for some tasks that would probably otherwise require manually looping over a collection (or using the spread syntax).
For example, we can use [`Math.max()`](../math/max) and [`Math.min()`](../math/min) to find out the maximum and minimum value in an array.
```
// min/max number in an array
const numbers = [5, 6, 2, 3, 7];
// using Math.min/Math.max apply
let max = Math.max.apply(null, numbers);
// This about equal to Math.max(numbers[0], β¦)
// or Math.max(5, 6, β¦)
let min = Math.min.apply(null, numbers);
// vs. simple loop based algorithm
max = -Infinity;
min = +Infinity;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
```
But beware: by using `apply()` (or the spread syntax) with an arbitrarily long arguments list, you run the risk of exceeding the JavaScript engine's argument length limit.
The consequences of calling a function with too many arguments (that is, more than tens of thousands of arguments) is unspecified and varies across engines. (The JavaScriptCore engine has a hard-coded [argument limit of 65536](https://bugs.webkit.org/show_bug.cgi?id=80797).) Most engines throw an exception; but there's no normative specification preventing other behaviors, such as arbitrarily limiting the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments `5, 6, 2, 3` had been passed to `apply` in the examples above, rather than the full array.
If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:
```
function minOfArray(arr) {
let min = Infinity;
const QUANTUM = 32768;
for (let i = 0; i < arr.length; i += QUANTUM) {
const submin = Math.min.apply(
null,
arr.slice(i, Math.min(i + QUANTUM, arr.length)),
);
min = Math.min(submin, min);
}
return min;
}
const min = minOfArray([5, 6, 2, 3, 7]);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function.prototype.apply](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function.prototype.apply) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `generic_arrays_as_arguments` | 17 | 12 | 4 | 9 | 5 | 6 | β€37 | 18 | 4 | 10.1 | 6 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`arguments`](../../functions/arguments) object
* [`Function.prototype.bind()`](bind)
* [`Function.prototype.call()`](call)
* [Functions and function scope](../../functions)
* [`Reflect.apply()`](../reflect/apply)
* [Spread syntax](../../operators/spread_syntax)
javascript Function.prototype.length Function.prototype.length
=========================
The `length` data property of a [`Function`](../function) instance indicates the number of parameters expected by the function.
Try it
------
Value
-----
A number.
| Property attributes of `Function.prototype.length` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | yes |
Description
-----------
A [`Function`](../function) object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the [rest parameter](../../functions/rest_parameters) and only includes parameters before the first one with a default value. By contrast, [`arguments.length`](../../functions/arguments/length) is local to a function and provides the number of arguments actually passed to the function.
The [`Function`](../function) constructor is itself a `Function` object. Its `length` data property has a value of `1`.
Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`.
Examples
--------
### Using function length
```
console.log(Function.length); // 1
console.log((() => {}).length); // 0
console.log(((a) => {}).length); // 1
console.log(((a, b) => {}).length); // 2 etc.
console.log(((...args) => {}).length);
// 0, rest parameter is not counted
console.log(((a, b = 1, c) => {}).length);
// 1, only parameters before the first one with
// a default value are counted
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-instances-length](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function-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 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `configurable_true` | 43 | 12 | 37 | No | 30 | 10 | 43 | 43 | 37 | 30 | 10 | 4.0 | 1.0 | 4.0.0 |
See also
--------
* [`Function`](../function)
javascript Function.prototype.call() Function.prototype.call()
=========================
The `call()` method calls the function with a given `this` value and arguments provided individually.
Try it
------
Syntax
------
```
call(thisArg)
call(thisArg, arg1)
call(thisArg, arg1, /\* β¦, \*/ argN)
```
### Parameters
`thisArg` The value to use as `this` when calling `func`. If the function is not in [strict mode](../../strict_mode), [`null`](../../operators/null) and [`undefined`](../undefined) will be replaced with the global object, and primitive values will be converted to objects.
`arg1, β¦, argN` Optional
Arguments for the function.
### Return value
The result of calling the function with the specified `this` value and arguments.
Description
-----------
**Note:** This function is almost identical to [`apply()`](apply), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** β for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`.
Normally, when calling a function, the value of [`this`](../../operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.
**Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](../../operators/new.target) is `undefined`, and classes throw an error because they can't be called without [`new`](../../operators/new). Use [`Reflect.construct()`](../reflect/construct) or [`extends`](../../classes/extends) instead.
Examples
--------
### Using call() to invoke a function and specifying the this value
In the example below, when we call `greet`, the value of `this` will be bound to object `obj`, even when `greet` is not a method of `obj`.
```
function greet() {
console.log(this.animal, "typically sleep between", this.sleepDuration);
}
const obj = {
animal: "cats",
sleepDuration: "12 and 16 hours",
};
greet.call(obj); // cats typically sleep between 12 and 16 hours
```
### Using call() to invoke a function without specifying the first argument
If the first `thisArg` parameter is omitted, it defaults to `undefined`. In non-strict mode, the `this` value is then substituted with [`globalThis`](../globalthis) (which is akin to the global object).
```
globalThis.globProp = "Wisen";
function display() {
console.log(`globProp value is ${this.globProp}`);
}
display.call(); // Logs "globProp value is Wisen"
```
In strict mode, the value of `this` is not substituted, so it stays as `undefined`.
```
"use strict";
globalThis.globProp = "Wisen";
function display() {
console.log(`globProp value is ${this.globProp}`);
}
display.call(); // throws TypeError: Cannot read the property of 'globProp' of undefined
```
### Transforming methods to utility functions
`call()` is almost equivalent to a normal function call, except that `this` is passed as a normal parameter instead of as the value that the function was accessed on. This is similar to how general-purpose utility functions work: instead of calling `array.map(callback)`, you use `map(array, callback)`, which avoids mutating `Array.prototype`, and allows you to use `map` with array-like objects that are not arrays (for example, [`arguments`](../../functions/arguments)).
Take [`Array.prototype.slice()`](../array/slice), for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:
```
const slice = Array.prototype.slice;
// ...
slice.call(arguments);
```
Note that you can't save `slice.call` and call it as a plain function, because the `call()` method also reads its `this` value, which is the function it should call. In this case, you can use [`bind()`](bind) to bind the value of `this` for `call()`. In the following piece of code, `slice()` is a bound version of [`Function.prototype.call()`](call), with the `this` value bound to [`Array.prototype.slice()`](../array/slice). This means that additional `call()` calls can be eliminated:
```
// Same as "slice" in the previous example
const unboundSlice = Array.prototype.slice;
const slice = Function.prototype.call.bind(unboundSlice);
// ...
slice(arguments);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function.prototype.call](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function.prototype.call) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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. |
See also
--------
* [`Function.prototype.bind()`](bind)
* [`Function.prototype.apply()`](apply)
* [`Reflect.apply()`](../reflect/apply)
* [Spread syntax](../../operators/spread_syntax)
* [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects)
javascript Function.prototype.name Function.prototype.name
=======================
The `name` property of a [`Function`](../function) instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously.
Try it
------
Value
-----
A string.
| Property attributes of `Function.prototype.name` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | yes |
**Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well.
Description
-----------
The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.
The `name` property is read-only and cannot be changed by the assignment operator:
```
function someFunction() {}
someFunction.name = 'otherFunction';
console.log(someFunction.name); // someFunction
```
To change it, use [`Object.defineProperty()`](../object/defineproperty).
The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred.
### Function declaration
The `name` property returns the name of a function declaration.
```
function doSomething() {}
doSomething.name; // "doSomething"
```
### Default-exported function declaration
An [`export default`](../../statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`.
```
// -- someModule.js --
export default function () {};
// -- main.js --
import someModule from "./someModule.js";
someModule.name; // "default"
```
### Function constructor
Functions created with the [`Function()`](function) constructor have name "anonymous".
```
new Function().name; // "anonymous"
```
### Function expression
If the function expression is named, that name is used as the `name` property.
```
const someFunction = function someFunctionName() {};
someFunction.name; // "someFunctionName"
```
Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name.
```
(function () {}).name; // ""
(() => {}).name; // ""
```
However, such cases are rare β usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate.
One practical case where the name cannot be inferred is a function returned from another function:
```
function getFoo() {
return () => {};
}
getFoo().name; // ""
```
### Variable declaration and method
Variables and methods can infer the name of an anonymous function from its syntactic position.
```
const f = function () {};
const object = {
someMethod: function () {}
};
console.log(f.name); // "f"
console.log(object.someMethod.name); // "someMethod"
```
The same applies to assignment:
```
let f;
f = () => {};
f.name; // "f"
```
### Initializer and default value
Functions in initializers (default values) of [destructuring](../../operators/destructuring_assignment#default_value), [default parameters](../../functions/default_parameters), [class fields](../../classes/public_class_fields), etc., will inherit the name of the bound identifier as their `name`.
```
const [f = () => {}] = [];
f.name; // "f"
const { someMethod: m = () => {} } = {};
m.name; // "m"
function foo(f = () => {}) {
console.log(f.name);
}
foo(); // "f"
class Foo {
static someMethod = () => {};
}
Foo.someMethod.name; // someMethod
```
### Shorthand method
```
const o = {
foo() {},
};
o.foo.name; // "foo";
```
### Bound function
[`Function.prototype.bind()`](bind) produces a function whose name is "bound " plus the function name.
```
function foo() {};
foo.bind({}).name; // "bound foo"
```
### Getter and setter
When using [`get`](../../functions/get) and [`set`](../../functions/set) accessor properties, "get" or "set" will appear in the function name.
```
const o = {
get foo() {},
set foo(x) {},
};
const descriptor = Object.getOwnPropertyDescriptor(o, "foo");
descriptor.get.name; // "get foo"
descriptor.set.name; // "set foo";
```
### Class
A class's name follows the same algorithm as function declarations and expressions.
```
class Foo {}
Foo.name; // "Foo"
```
**Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](../../classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [an example](#telling_the_constructor_name_of_an_object) below.
### Symbol as function name
If a [`Symbol`](../symbol) is used a function name and the symbol has a description, the method's name is the description in square brackets.
```
const sym1 = Symbol("foo");
const sym2 = Symbol();
const o = {
[sym1]() {},
[sym2]() {},
};
o[sym1].name; // "[foo]"
o[sym2].name; // "[]"
```
### Private property
Private fields and private methods have the hash (`#`) as part of their names.
```
class Foo {
#field = () => {};
#method() {}
getNames() {
console.log(this.#field.name);
console.log(this.#method.name);
}
}
new Foo().getNames();
// "#field"
// "#method"
```
Examples
--------
### Telling the constructor name of an object
You can use `obj.constructor.name` to check the "class" of an object.
```
function Foo() {} // Or: class Foo {}
const fooInstance = new Foo();
console.log(fooInstance.constructor.name); // "Foo"
```
However, because static members will become own properties of the class, we can't obtain the class name for virtually any class with a static method property `name()`:
```
class Foo {
constructor() {}
static name() {}
}
```
With a `static name()` method `Foo.name` no longer holds the actual class name but a reference to the `name()` function object. Trying to obtain the class of `fooInstance` via `fooInstance.constructor.name` won't give us the class name at all, but instead a reference to the static class method. Example:
```
const fooInstance = new Foo();
console.log(fooInstance.constructor.name); // Ζ name() {}
```
Due to the existence of static fields, `name` may not be a function either.
```
class Foo {
static name = 123;
}
console.log(new Foo().constructor.name); // 123
```
If a class has a static property called `name`, it will also become *writable*. The built-in definition in the absence of a custom static definition is *read-only*:
```
Foo.name = 'Hello';
console.log(Foo.name); // "Hello" if class Foo has a static "name" property, but "Foo" if not.
```
Therefore you may not rely on the built-in `name` property to always hold a class's name.
### JavaScript compressors and minifiers
**Warning:** Be careful when using the `name` property with source-code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build time.
Source code such as:
```
function Foo() {};
const foo = new Foo();
if (foo.constructor.name === 'Foo') {
console.log("'foo' is an instance of 'Foo'");
} else {
console.log('Oops!');
}
```
may be compressed to:
```
function a() {};
const b = new a();
if (b.constructor.name === 'Foo') {
console.log("'foo' is an instance of 'Foo'");
} else {
console.log('Oops!');
}
```
In the uncompressed version, the program runs into the truthy branch and logs "'foo' is an instance of 'Foo'" β whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the `name` property, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function has a particular name.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-instances-name](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function-instances-name) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 15 | 14 | 1 | No | 10.5 | 6 | 4.4 | 18 | 4 | 11 | 6 | 1.0 | 1.0 | 0.10.0 |
| `configurable_true` | 43 | 14 | 38 | No | 30 | 10 | 43 | 43 | 38 | 30 | 10 | 4.0 | 1.0 | 4.0.0 |
| `inferred_names` | 51 | 79
14-79
Names for functions defined in a dictionary are properly assigned; however, anonymous functions defined on a var/let variable assignment have blank names. | 53 | No | 38 | 10 | 51 | 51 | 53 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* A polyfill for functions' `.name` property is available in [`core-js`](https://github.com/zloirock/core-js#ecmascript-function)
* [`Function`](../function)
| programming_docs |
javascript Function.prototype.caller Function.prototype.caller
=========================
**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.
**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.
The `caller` accessor property of [`Function`](../function) instances represents the function that invoked this function. For [strict](../../strict_mode), arrow, async, and generator functions, accessing the `caller` property throws a [`TypeError`](../typeerror).
Description
-----------
If the function `f` was invoked by the top-level code, the value of `f.caller` is [`null`](../../operators/null); otherwise it's the function that called `f`. If the function that called `f` is a strict mode function, the value of `f.caller` is also `null`.
In [strict mode](../../strict_mode), accessing `caller` of a function throws an error. This is to prevent a function from being able to "walk the stack", which both poses security risks and severely limits the possibility of optimizations like inlining and tail-call optimization. For more explanation, you can read [the rationale for the deprecation of `arguments.callee`](../../functions/arguments/callee#description).
Note that the only behavior specified by the ECMAScript specification is that `Function.prototype` has an initial `caller` accessor that unconditionally throws a [`TypeError`](../typeerror) for any `get` or `set` request (known as a "poison pill accessor"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions, in which case it must not have the value of a strict mode function. The actual behavior of the `caller` property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill `Function.prototype.caller` accessor to specially handle `this` values that are non-strict functions.
```
(function f() {
if (Object.hasOwn(f, "caller")) {
console.log(
"caller is an own property with descriptor",
Object.getOwnPropertyDescriptor(f, "caller")
);
} else {
console.log(
"f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller"
);
console.log(
Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(f),
"caller"
).get.call(f)
);
}
})();
// In Chrome:
// caller is an own property with descriptor {value: null, writable: false, enumerable: false, configurable: false}
// In Firefox:
// f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller
// null
```
This property replaces the obsolete `arguments.caller` property of the [`arguments`](../../functions/arguments) object.
The special property `__caller__`, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.
Examples
--------
### Checking the value of a function's caller property
The following code checks the value a function's `caller` property.
```
function myFunc() {
if (myFunc.caller === null) {
return "The function was called from the top!";
} else {
return `This function's caller was ${myFunc.caller}`;
}
}
```
### Reconstructing the stack and recursion
Note that in case of recursion, you can't reconstruct the call stack using this property. Consider:
```
function f(n) {
g(n - 1);
}
function g(n) {
if (n > 0) {
f(n);
} else {
stop();
}
}
f(2);
```
At the moment `stop()` is called the call stack will be:
```
f(2) -> g(1) -> f(1) -> g(0) -> stop()
```
The following is true:
```
stop.caller === g && f.caller === g && g.caller === f;
```
so if you tried to get the stack trace in the `stop()` function like this:
```
let f = stop;
let stack = "Stack trace:";
while (f) {
stack += `\n${f.name}`;
f = f.caller;
}
```
the loop would never stop.
### Strict mode caller
If the caller is a strict mode function, the value of `caller` is `null`.
```
function callerFunc() {
calleeFunc();
}
function strictCallerFunc() {
"use strict";
calleeFunc();
}
function calleeFunc() {
console.log(calleeFunc.caller);
}
(function () {
callerFunc();
})();
// Logs [Function: callerFunc]
(function () {
strictCallerFunc();
})();
// Logs null
```
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 |
| `caller` | 1 | 12 | 1 | 8 | 9.6 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Function.prototype.name`](name)
* [`arguments`](../../functions/arguments)
javascript Function.prototype.toString() Function.prototype.toString()
=============================
The `toString()` method returns a string representing the source code of the specified [`Function`](../function).
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the source code of the function.
Description
-----------
The [`Function`](../function) object overrides the `toString()` method inherited from [`Object`](../object); it does not inherit [`Object.prototype.toString`](../object/tostring). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function.
JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string.
The `toString()` method will throw a [`TypeError`](../typeerror) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object.
```
Function.prototype.toString.call('foo'); // throws TypeError
```
If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](bind), or other non-JavaScript functions, then `toString()` returns a *native function string* which looks like
```
"function someName() { [native code] }"
```
For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`.
**Note:** This means using [`eval()`](../eval) on native function strings is a guaranteed syntax error.
If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return:
```
"function anonymous(a,b\n) {\nreturn a + b\n}"
```
Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments β or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [compatibility table](#browser_compatibility).
Examples
--------
### Comparing actual source code and toString results
```
function test(fn) {
console.log(fn.toString());
}
function f() {}
class A { a() {} }
function\* g() {}
test(f); // "function f() {}"
test(A); // "class A { a() {} }"
test(g); // "function\* g() {}"
test((a) => a); // "(a) => a"
test({ a() {} }.a); // "a() {}"
test({ \*a() {} }.a); // "\*a() {}"
test({ [0](){} }[0]); // "[0]() {}"
test(Object.getOwnPropertyDescriptor({
get a() {},
}, "a").get); // "get a() {}"
test(Object.getOwnPropertyDescriptor({
set a(x) {},
}, "a").set); // "set a(x) {}"
test(Function.prototype.toString); // "function toString() { [native code] }"
test(function f() {}.bind(0)); // "function () { [native code] }"
test(Function("a", "b")); // function anonymous(a\n) {\nb\n}
```
Note that after the `Function.prototype.toString()` revision, when `toString()` is called, implementations are never allowed to synthesize a function's source that is not a native function string. The method always returns the exact source code used to create the function β including the [getter](../../functions/get) and [setter](../../functions/set) examples above. The [`Function`](../../functions) constructor itself has the capability of synthesizing the source code for the function (and is therefore a form of implicit [`eval()`](../eval)).
### Getting source text of a function
It is possible to get the source text of a function by coercing it to a string β for example, by wrapping it in a template literal:
```
function foo() { return 'bar' }
console.log(`${foo}`); // "function foo() { return 'bar' }"
```
This source text is *exact*, including any interspersed comments (which won't be stored by the engine's internal representation otherwise).
```
function foo/\* a comment \*/() { return 'bar' }
console.log(foo.toString()); // "function foo/\* a comment \*/() { return 'bar' }"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function.prototype.tostring](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function.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 | 5 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString_revision` | 66 | 79 | 54 | No | 53 | No | 66 | 66 | 54 | 47 | No | 9.0 | 1.0 | No |
See also
--------
* [`Object.prototype.toString()`](../object/tostring)
javascript Function.prototype.arguments Function.prototype.arguments
============================
**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.
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
**Note:** The `arguments` property of [`Function`](../function) objects is deprecated. The recommended way to access the `arguments` object is to refer to the variable [`arguments`](../../functions/arguments) available within functions.
The `arguments` accessor property of [`Function`](../function) instances represents the arguments passed to this function. For [strict](../../strict_mode), arrow, async, and generator functions, accessing the `arguments` property throws a [`TypeError`](../typeerror).
Description
-----------
The value of `arguments` is an array-like object corresponding to the arguments passed to a function.
In the case of recursion, i.e. if function `f` appears several times on the call stack, the value of `f.arguments` represents the arguments corresponding to the most recent invocation of the function.
The value of the `arguments` property is normally [`null`](../../operators/null) if there is no outstanding invocation of the function in progress (that is, the function has been called but has not yet returned).
Note that the only behavior specified by the ECMAScript specification is that `Function.prototype` has an initial `arguments` accessor that unconditionally throws a [`TypeError`](../typeerror) for any `get` or `set` request (known as a "poison pill accessor"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions. The actual behavior of the `arguments` property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill `Function.prototype.arguments` accessor to specially handle `this` values that are non-strict functions.
```
(function f() {
if (Object.hasOwn(f, "arguments")) {
console.log(
"arguments is an own property with descriptor",
Object.getOwnPropertyDescriptor(f, "arguments")
);
} else {
console.log(
"f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments"
);
console.log(
Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(f),
"arguments"
).get.call(f)
);
}
})();
// In Chrome:
// arguments is an own property with descriptor {value: Arguments(0), writable: false, enumerable: false, configurable: false}
// In Firefox:
// f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments
// Arguments { β¦ }
```
Examples
--------
### Using the arguments property
```
function f(n) {
g(n - 1);
}
function g(n) {
console.log(`before: ${g.arguments[0]}`);
if (n > 0) {
f(n);
}
console.log(`after: ${g.arguments[0]}`);
}
f(2);
console.log(`returned: ${g.arguments}`);
// Logs:
// before: 1
// before: 0
// after: 0
// after: 1
// returned: null
```
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 |
| `arguments` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`arguments`](../../functions/arguments) object
* [Functions and function scope](../../functions)
javascript Function() constructor Function() constructor
======================
The `Function()` constructor creates a new [`Function`](../function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as [`eval()`](../eval). However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only.
Try it
------
Syntax
------
```
new Function(functionBody)
new Function(arg0, functionBody)
new Function(arg0, arg1, functionBody)
new Function(arg0, arg1, /\* β¦ ,\*/ argN, functionBody)
Function(functionBody)
Function(arg0, functionBody)
Function(arg0, arg1, functionBody)
Function(arg0, arg1, /\* β¦ ,\*/ argN, functionBody)
```
**Note:** `Function()` can be called with or without [`new`](../../operators/new). Both create a new `Function` instance.
### Parameters
`argN` Optional
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/en-US/docs/Glossary/Identifier), [rest parameter](../../functions/rest_parameters), or [destructured](../../operators/destructuring_assignment) parameter, optionally with a [default](../../functions/default_parameters)), or a list of such strings separated with commas.
As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` β or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.)
`functionBody` A string containing the JavaScript statements comprising the function definition.
Description
-----------
`Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](../../operators/function) or [function declaration](../../statements/function) and calling it within your code, because such functions are parsed with the rest of the code.
All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion:
```
`function anonymous(${args.join(",")}
) {
${functionBody}
}`
```
This is observable by calling the function's [`toString()`](tostring) method.
However, unlike normal [function expressions](../../operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](../../strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](../../functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function:
```
const recursiveFn = new Function("count", `
(function recursiveFn(count) {
if (count < 0) {
return;
}
console.log(count);
recursiveFn(count - 1);
})(count);
`);
```
Note that the two dynamic parts of the assembled source β the parameters list `args.join(",")` and `functionBody` β will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts.
```
new Function("/\*", "\*/) {");
// SyntaxError: Unexpected end of arg string
// Doesn't become "function anonymous(/\*) {\*/) {}"
```
Examples
--------
### Specifying arguments with the Function constructor
The following code creates a `Function` object that takes two arguments.
```
// Example can be run directly in your JavaScript console
// Create a function that takes two arguments, and returns the sum of those arguments
const adder = new Function('a', 'b', 'return a + b');
// Call the function
adder(2, 6);
// 8
```
The arguments `a` and `b` are formal argument names that are used in the function body, `return a + b`.
### Creating a function object from a function declaration or function expression
```
// The function constructor can take in multiple statements separated by a semicolon. Function expressions require a return statement with the function's name
// Observe that new Function is called. This is so we can call the function we created directly afterwards
const sumOfArray = new Function('const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray')();
// call the function
sumOfArray([1, 2, 3, 4]);
// 10
// If you don't call new Function at the point of creation, you can use the Function.call() method to call it
const findLargestNumber = new Function('function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber');
// call the function
findLargestNumber.call({}).call({}, [2, 4, 1, 8, 5]);
// 8
// Function declarations do not require a return statement
const sayHello = new Function('return function (name) { return `Hello, ${name}` }')();
// call the function
sayHello('world');
// Hello, world
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-constructor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function-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 |
| `Function` | 1 | 12 | 1 | 4 | 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)
* [Functions](../../functions)
| programming_docs |
javascript Math.clz32() Math.clz32()
============
The `Math.clz32()` static method returns the number of leading zero bits in the 32-bit binary representation of a number.
Try it
------
Syntax
------
```
Math.clz32(x)
```
### Parameters
`x` A number.
### Return value
The number of leading zero bits in the 32-bit binary representation of `x`.
Description
-----------
`clz32` is short for **C**ount**L**eading**Z**eros**32**.
If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer.
If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned.
This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org).
Examples
--------
### Using Math.clz32()
```
Math.clz32(1); // 31
Math.clz32(1000); // 22
Math.clz32(); // 32
const stuff = [NaN, Infinity, -Infinity, 0, -0, false, null, undefined, 'foo', {}, []];
stuff.every((n) => Math.clz32(n) === 32); // true
Math.clz32(true); // 31
Math.clz32(3.5); // 30
```
### Implementing Count Leading Ones and beyond
At present, there is no `Math.clon` for "Count Leading Ones" (named "clon", not "clo", because "clo" and "clz" are too similar especially for non-English-speaking people). However, a `clon` function can easily be created by inverting the bits of a number and passing the result to `Math.clz32`. Doing this will work because the inverse of 1 is 0 and vice versa. Thus, inverting the bits will inverse the measured quantity of 0's (from `Math.clz32`), thereby making `Math.clz32` count the number of ones instead of counting the number of zeros.
Consider the following 32-bit word:
```
const a = 32776; // 00000000000000001000000000001000 (16 leading zeros)
Math.clz32(a); // 16
const b = ~32776; // 11111111111111110111111111110111 (32776 inverted, 0 leading zeros)
Math.clz32(b); // 0 (this is equal to how many leading one's there are in a)
```
Using this logic, a `clon` function can be created as follows:
```
const clz = Math.clz32;
function clon(integer) {
return clz(~integer);
}
```
Further, this technique could be extended to create a jumpless "Count Trailing Zeros" function, as seen below. The `ctrz` function takes a bitwise AND of the integer with its two's complement. By how two's complement works, all trailing zeros will be converted to ones, and then when adding 1, it would be carried over until the first `0` (which was originally a `1`) is reached. All bits higher than this one stay the same and are inverses of the original integer's bits. Therefore, when doing bitwise AND with the original integer, all higher bits become `0`, which can be counted with `clz`. The number of trailing zeros, plus the first `1` bit, plus the leading bits that were counted by `clz`, total to 32.
```
function ctrz(integer) {
integer >>>= 0; // coerce to Uint32
if (integer === 0) {
// skipping this step would make it return -1
return 32;
}
integer &= -integer; // equivalent to `int = int & (~int + 1)`
return 31 - clz(integer);
}
```
Then we can define a "Count Trailing Ones" function like so:
```
function ctron(integer) {
return ctrz(~integer);
}
```
These helper functions can be made into an [asm.js](https://developer.mozilla.org/en-US/docs/Games/Tools/asm.js) module for a potential performance improvement.
```
const countTrailsMethods = (function (stdlib, foreign, heap) {
"use asm";
const clz = stdlib.Math.clz32;
// count trailing zeros
function ctrz(integer) {
integer = integer | 0; // coerce to an integer
if ((integer | 0) == 0) {
// skipping this step would make it return -1
return 32;
}
// Note: asm.js doesn't have compound assignment operators such as &=
integer = integer & -integer; // equivalent to `int = int & (~int + 1)`
return 31 - clz(integer) | 0;
}
// count trailing ones
function ctron(integer) {
integer = integer | 0; // coerce to an integer
return ctrz(~integer) | 0;
}
// asm.js demands plain objects:
return { ctrz: ctrz, ctron: ctron };
})(window, null, null);
const { ctrz, ctron } = countTrailsMethods;
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.clz32](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.clz32) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `clz32` | 38 | 12 | 31 | No | 25 | 7 | 38 | 38 | 31 | 25 | 7 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.clz32` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math`](../math)
* [`Math.imul`](imul)
javascript Math.atan() Math.atan()
===========
The `Math.atan()` static method returns the inverse tangent (in radians) of a number, that is
πΌπππ.ππππ ( π‘ ) = arctan ( x ) = the unique y β [ β Ο 2 , Ο 2 ] such that tan ( y ) = x \mathtt{\operatorname{Math.atan}(x)} = \arctan(x) = \text{the unique } y \in \left[-\frac{\pi}{2}, \frac{\pi}{2}\right] \text{ such that } \tan(y) = x
Try it
------
Syntax
------
```
Math.atan(x)
```
### Parameters
`x` A number.
### Return value
The inverse tangent (angle in radians between - Ο 2 -\frac{\pi}{2} and Ο 2 \frac{\pi}{2} , inclusive) of `x`. If `x` is [`Infinity`](../infinity), it returns Ο 2 \frac{\pi}{2} . If `x` is `-Infinity`, it returns - Ο 2 -\frac{\pi}{2} .
Description
-----------
Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.atan()
```
Math.atan(-Infinity); // -1.5707963267948966 (-Ο/2)
Math.atan(-0); // -0
Math.atan(0); // 0
Math.atan(1); // 0.7853981633974483 (Ο/4)
Math.atan(Infinity); // 1.5707963267948966 (Ο/2)
// The angle that the line (0,0) -- (x,y) forms with the x-axis in a Cartesian coordinate system
const theta = (x, y) => Math.atan(y / x);
```
Note that you may want to avoid the `theta` function and use [`Math.atan2()`](atan2) instead, which has a wider range (between -Ο and Ο) and avoids outputting `NaN` for cases such as when `x` is `0`.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.atan](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.atan) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `atan` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.acos()`](acos)
* [`Math.asin()`](asin)
* [`Math.atan2()`](atan2)
* [`Math.cos()`](cos)
* [`Math.sin()`](sin)
* [`Math.tan()`](tan)
javascript Math.asin() Math.asin()
===========
The `Math.asin()` static method returns the inverse sine (in radians) of a number. That is,
β x β [ β 1 , 1 ] , πΌπππ.ππππ ( π‘ ) = arcsin ( x ) = the unique y β [ β Ο 2 , Ο 2 ] such that sin ( y ) = x \forall x \in [{-1}, 1],;\mathtt{\operatorname{Math.asin}(x)} = \arcsin(x) = \text{the unique } y \in \left[-\frac{\pi}{2}, \frac{\pi}{2}\right] \text{ such that } \sin(y) = x
Try it
------
Syntax
------
```
Math.asin(x)
```
### Parameters
`x` A number between -1 and 1, inclusive, representing the angle's sine value.
### Return value
The inverse sine (angle in radians between - Ο 2 -\frac{\pi}{2} and Ο 2 \frac{\pi}{2} , inclusive) of `x`. If `x` is less than -1 or greater than 1, returns [`NaN`](../nan).
Description
-----------
Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.asin()
```
Math.asin(-2); // NaN
Math.asin(-1); // -1.5707963267948966 (-Ο/2)
Math.asin(-0); // -0
Math.asin(0); // 0
Math.asin(0.5); // 0.5235987755982989 (Ο/6)
Math.asin(1); // 1.5707963267948966 (Ο/2)
Math.asin(2); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.asin](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.asin) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `asin` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.acos()`](acos)
* [`Math.atan()`](atan)
* [`Math.atan2()`](atan2)
* [`Math.cos()`](cos)
* [`Math.sin()`](sin)
* [`Math.tan()`](tan)
javascript Math.cosh() Math.cosh()
===========
The `Math.cosh()` static method returns the hyperbolic cosine of a number. That is,
πΌπππ.ππππ ( π‘ ) = cosh ( x ) = e x + e β x 2 \mathtt{\operatorname{Math.cosh}(x)} = \cosh(x) = \frac{\mathrm{e}^x + \mathrm{e}^{-x}}{2}
Try it
------
Syntax
------
```
Math.cosh(x)
```
### Parameters
`x` A number.
### Return value
The hyperbolic cosine of `x`.
Description
-----------
Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.cosh()
```
Math.cosh(-Infinity); // Infinity
Math.cosh(-1); // 1.5430806348152437
Math.cosh(-0); // 1
Math.cosh(0); // 1
Math.cosh(1); // 1.5430806348152437
Math.cosh(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.cosh](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.cosh) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `cosh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.cosh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.acosh()`](acosh)
* [`Math.asinh()`](asinh)
* [`Math.atanh()`](atanh)
* [`Math.sinh()`](sinh)
* [`Math.tanh()`](tanh)
javascript Math.asinh() Math.asinh()
============
The `Math.asinh()` static method returns the inverse hyperbolic sine of a number. That is,
πΌπππ.πππππ ( π‘ ) = arsinh ( x ) = the unique y such that sinh ( y ) = x = ln ( x + x 2 + 1 ) \begin{aligned}\mathtt{\operatorname{Math.asinh}(x)} &= \operatorname{arsinh}(x) = \text{the unique } y \text{ such that } \sinh(y) = x \&= \ln\left(x + \sqrt{x^2 + 1}\right)\end{aligned}
Try it
------
Syntax
------
```
Math.asinh(x)
```
### Parameters
`x` A number.
### Return value
The inverse hyperbolic sine of `x`.
Description
-----------
Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.asinh()
```
Math.asinh(-Infinity); // -Infinity
Math.asinh(-1); // -0.881373587019543
Math.asinh(-0); // -0
Math.asinh(0); // 0
Math.asinh(1); // 0.881373587019543
Math.asinh(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.asinh](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.asinh) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `asinh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.asinh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.acosh()`](acosh)
* [`Math.atanh()`](atanh)
* [`Math.cosh()`](cosh)
* [`Math.sinh()`](sinh)
* [`Math.tanh()`](tanh)
javascript Math.PI Math.PI
=======
The `Math.PI` property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159.
Try it
------
Value
-----
πΌπππ.πΏπΈ = Ο β 3.14159 \mathtt{\mi{Math.PI}} = \pi \approx 3.14159
| Property attributes of `Math.PI` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.PI
The following function uses `Math.PI` to calculate the circumference of a circle with a passed radius.
```
function calculateCircumference(radius) {
return Math.PI \* (radius + radius);
}
calculateCircumference(1); // 6.283185307179586
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.pi](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.pi) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `PI` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math`](../math)
javascript Math.trunc() Math.trunc()
============
The `Math.trunc()` static method returns the integer part of a number by removing any fractional digits.
Try it
------
Syntax
------
```
Math.trunc(x)
```
### Parameters
`x` A number.
### Return value
The integer part of `x`.
Description
-----------
Unlike the other three `Math` methods: [`Math.floor()`](floor), [`Math.ceil()`](ceil) and [`Math.round()`](round), the way `Math.trunc()` works is very simple. It *truncates* (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.
Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.trunc()
```
Math.trunc(-Infinity); // -Infinity
Math.trunc("-1.123"); // -1
Math.trunc(-0.123); // -0
Math.trunc(-0); // -0
Math.trunc(0); // 0
Math.trunc(0.123); // 0
Math.trunc(13.37); // 13
Math.trunc(42.84); // 42
Math.trunc(Infinity); // Infinity
```
### Using bitwise no-ops to truncate numbers
**Warning:** This is not a polyfill for `Math.trunc()` because of non-negligible edge cases.
Bitwise operations convert their operands to 32-bit integers, which people have historically taken advantage of to truncate float-point numbers. Common techniques include:
```
const original = 3.14;
const truncated1 = ~~original; // Double negation
const truncated2 = original & -1; // Bitwise AND with -1
const truncated3 = original | 0; // Bitwise OR with 0
const truncated4 = original ^ 0; // Bitwise XOR with 0
const truncated5 = original >> 0; // Bitwise shifting by 0
```
Beware that this is essentially `toInt32`, which is not the same as `Math.trunc`. When the value does not satisfy -231 - 1 < `value` < 231 (-2147483649 < `value` < 2147483648), the conversion would overflow.
```
const a = ~~2147483648; // -2147483648
const b = ~~-2147483649; // 2147483647
const c = ~~4294967296; // 0
```
Only use `~~` as a substitution for `Math.trunc()` when you are confident that the range of input falls within the range of 32-bit integers.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.trunc](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.trunc) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `trunc` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.trunc` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/math.polyfill.js)
* [`Math.abs()`](abs)
* [`Math.ceil()`](ceil)
* [`Math.floor()`](floor)
* [`Math.round()`](round)
* [`Math.sign()`](sign)
javascript Math.LN2 Math.LN2
========
The `Math.LN2` property represents the natural logarithm of 2, approximately 0.693:
Try it
------
Value
-----
πΌπππ.π»π½πΈ = ln ( 2 ) β 0.693 \mathtt{\mi{Math.LN2}} = \ln(2) \approx 0.693
| Property attributes of `Math.LN2` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.LN2
The following function returns the natural log of 2:
```
function getNatLog2() {
return Math.LN2;
}
getNatLog2(); // 0.6931471805599453
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.ln2](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.ln2) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `LN2` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log2()`](log2)
javascript Math.log2() Math.log2()
===========
The `Math.log2()` static method returns the base 2 logarithm of a number. That is
β x > 0 , πΌπππ.ππππΈ ( π‘ ) = log 2 ( x ) = the unique y such that 2 y = x \forall x > 0,;\mathtt{\operatorname{Math.log2}(x)} = \log\_2(x) = \text{the unique } y \text{ such that } 2^y = x
Try it
------
Syntax
------
```
Math.log2(x)
```
### Parameters
`x` A number greater than or equal to 0.
### Return value
The base 2 logarithm of `x`. If `x < 0`, returns [`NaN`](../nan).
Description
-----------
Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant [`Math.LOG2E`](log2e), which is 1 / [`Math.LN2`](ln2).
Examples
--------
### Using Math.log2()
```
Math.log2(-2); // NaN
Math.log2(-0); // -Infinity
Math.log2(0); // -Infinity
Math.log2(1); // 0
Math.log2(2); // 1
Math.log2(3); // 1.584962500721156
Math.log2(1024); // 10
Math.log2(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.log2](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.log2) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `log2` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.log2` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log10()`](log10)
* [`Math.log1p()`](log1p)
* [`Math.pow()`](pow)
| programming_docs |
javascript Math.LOG2E Math.LOG2E
==========
The `Math.LOG2E` property represents the base 2 logarithm of <e>, approximately 1.442.
Try it
------
Value
-----
πΌπππ.π»πΎπΆπΈπ΄ = log 2 ( e ) β 1.442 \mathtt{\mi{Math.LOG2E}} = \log\_2(\mathrm{e}) \approx 1.442
| Property attributes of `Math.LOG2E` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.LOG2E
The following function returns the base 2 logarithm of e:
```
function getLog2e() {
return Math.LOG2E;
}
getLog2e(); // 1.4426950408889634
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.log2e](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.log2e) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `LOG2E` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log2()`](log2)
javascript Math.round() Math.round()
============
The `Math.round()` static method returns the value of a number rounded to the nearest integer.
Try it
------
Syntax
------
```
Math.round(x)
```
### Parameters
`x` A number.
### Return value
The value of `x` rounded to the nearest integer.
Description
-----------
If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +β.
**Note:** This differs from many languages' `round()` functions, which often round half-increments *away from zero*, giving a different result in the case of negative numbers with a fractional part of exactly 0.5.
`Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](floor). When `x` is -0, or -0.5 β€ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent.
Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor).
Examples
--------
### Using round
```
Math.round(-Infinity); // -Infinity
Math.round(-20.51); // -21
Math.round(-20.5); // -20
Math.round(-0.1); // -0
Math.round(0); // 0
Math.round(20.49); // 20
Math.round(20.5); // 21
Math.round(42); // 42
Math.round(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.round](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.round) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `round` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.prototype.toPrecision()`](../number/toprecision)
* [`Number.prototype.toFixed()`](../number/tofixed)
* [`Math.abs()`](abs)
* [`Math.ceil()`](ceil)
* [`Math.floor()`](floor)
* [`Math.sign()`](sign)
* [`Math.trunc()`](trunc)
javascript Math.cos() Math.cos()
==========
The `Math.cos()` static method returns the cosine of a number in radians.
Try it
------
Syntax
------
```
Math.cos(x)
```
### Parameters
`x` A number representing an angle in radians.
### Return value
The cosine of `x`, between -1 and 1, inclusive. If `x` is [`Infinity`](../infinity), `-Infinity`, or [`NaN`](../nan), returns [`NaN`](../nan).
Description
-----------
Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.cos()
```
Math.cos(-Infinity); // NaN
Math.cos(-0); // 1
Math.cos(0); // 1
Math.cos(1); // 0.5403023058681398
Math.cos(Math.PI); // -1
Math.cos(2 \* Math.PI); // 1
Math.cos(Infinity); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.cos](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.cos) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `cos` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.acos()`](acos)
* [`Math.asin()`](asin)
* [`Math.atan()`](atan)
* [`Math.atan2()`](atan2)
* [`Math.sin()`](sin)
* [`Math.tan()`](tan)
javascript Math.LOG10E Math.LOG10E
===========
The `Math.LOG10E` property represents the base 10 logarithm of <e>, approximately 0.434.
Try it
------
Value
-----
πΌπππ.π»πΎπΆπ·πΆπ΄ = log 10 ( e ) β 0.434 \mathtt{\mi{Math.LOG10E}} = \log\_{10}(\mathrm{e}) \approx 0.434
| Property attributes of `Math.LOG10E` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.LOG10E
The following function returns the base 10 logarithm of e:
```
function getLog10e() {
return Math.LOG10E;
}
getLog10e(); // 0.4342944819032518
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.log10e](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.log10e) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `LOG10E` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log10()`](log10)
javascript Math.sqrt() Math.sqrt()
===========
The `Math.sqrt()` static method returns the square root of a number. That is
β x β₯ 0 , πΌπππ.ππππ ( π‘ ) = x = the unique y β₯ 0 such that y 2 = x \forall x \geq 0,;\mathtt{\operatorname{Math.sqrt}(x)} = \sqrt{x} = \text{the unique } y \geq 0 \text{ such that } y^2 = x
Try it
------
Syntax
------
```
Math.sqrt(x)
```
### Parameters
`x` A number greater than or equal to 0.
### Return value
The square root of `x`, a nonnegative number. If `x < 0`, returns [`NaN`](../nan).
Description
-----------
Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.sqrt()
```
Math.sqrt(-1); // NaN
Math.sqrt(-0); // -0
Math.sqrt(0); // 0
Math.sqrt(1); // 1
Math.sqrt(2); // 1.414213562373095
Math.sqrt(9); // 3
Math.sqrt(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.sqrt](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sqrt) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sqrt` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.cbrt()`](cbrt)
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.pow()`](pow)
javascript Math.sign() Math.sign()
===========
The `Math.sign()` static method returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is.
Try it
------
Syntax
------
```
Math.sign(x)
```
### Parameters
`x` A number.
### Return value
A number representing the sign of `x`:
* If `x` is positive, returns `1`.
* If `x` is negative, returns `-1`.
* If `x` is positive zero, returns `0`.
* If `x` is negative zero, returns `-0`.
* Otherwise, returns [`NaN`](../nan).
Description
-----------
Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.sign()
```
Math.sign(3); // 1
Math.sign(-3); // -1
Math.sign("-3"); // -1
Math.sign(0); // 0
Math.sign(-0); // -0
Math.sign(NaN); // NaN
Math.sign("foo"); // NaN
Math.sign(); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.sign](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sign) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sign` | 38 | 12 | 25 | No | 25 | 9 | 38 | 38 | 25 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.sign` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/math.polyfill.js)
* [`Math.abs()`](abs)
* [`Math.ceil()`](ceil)
* [`Math.floor()`](floor)
* [`Math.round()`](round)
* [`Math.trunc()`](trunc)
javascript Math.tanh() Math.tanh()
===========
The `Math.tanh()` static method returns the hyperbolic tangent of a number. That is,
πΌπππ.ππππ ( π‘ ) = tanh ( x ) = sinh ( x ) cosh ( x ) = e x β e β x e x + e β x = e 2 x β 1 e 2 x + 1 \mathtt{\operatorname{Math.tanh}(x)} = \tanh(x) = \frac{\sinh(x)}{\cosh(x)} = \frac{\mathrm{e}^x - \mathrm{e}^{-x}}{\mathrm{e}^x + \mathrm{e}^{-x}} = \frac{\mathrm{e}^{2x} - 1}{\mathrm{e}^{2x}+1}
Try it
------
Syntax
------
```
Math.tanh(x)
```
### Parameters
`x` A number.
### Return value
The hyperbolic tangent of `x`.
Description
-----------
Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.tanh()
```
Math.tanh(-Infinity); // -1
Math.tanh(-0); // -0
Math.tanh(0); // 0
Math.tanh(1); // 0.7615941559557649
Math.tanh(Infinity); // 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.tanh](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.tanh) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `tanh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.tanh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.acosh()`](acosh)
* [`Math.asinh()`](asinh)
* [`Math.atanh()`](atanh)
* [`Math.cosh()`](cosh)
* [`Math.sinh()`](sinh)
javascript Math.cbrt() Math.cbrt()
===========
The `Math.cbrt()` static method returns the cube root of a number. That is
πΌπππ.ππππ ( π‘ ) = x 3 = the unique y such that y 3 = x \mathtt{\operatorname{Math.cbrt}(x)} = \sqrt[3]{x} = \text{the unique } y \text{ such that } y^3 = x
Try it
------
Syntax
------
```
Math.cbrt(x)
```
### Parameters
`x` A number.
### Return value
The cube root of `x`.
Description
-----------
Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.cbrt()
```
Math.cbrt(-Infinity); // -Infinity
Math.cbrt(-1); // -1
Math.cbrt(-0); // -0
Math.cbrt(0); // 0
Math.cbrt(1); // 1
Math.cbrt(2); // 1.2599210498948732
Math.cbrt(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.cbrt](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.cbrt) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `cbrt` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.cbrt` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.pow()`](pow)
* [`Math.sqrt()`](sqrt)
javascript Math.pow() Math.pow()
==========
The `Math.pow()` static method returns the value of a base raised to a power. That is
πΌπππ.πππ ( π‘ , π’ ) = x y \mathtt{\operatorname{Math.pow}(x, y)} = x^y
Try it
------
Syntax
------
```
Math.pow(base, exponent)
```
### Parameters
`base` The base number.
`exponent` The exponent number.
### Return value
A number representing `base` taken to the power of `exponent`. Returns [`NaN`](../nan) in one of the following cases:
* `exponent` is `NaN`.
* `base` is `NaN` and `exponent` is not `0`.
* `base` is Β±1 and `exponent` is Β±`Infinity`.
* `base < 0` and `exponent` is not an integer.
Description
-----------
`Math.pow()` is equivalent to the [`**`](../../operators/exponentiation) operator, except `Math.pow()` only accepts numbers.
`Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where [`NaN`](../nan) doesn't propagate through mathematical operations β it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (Β±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior.
Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.pow()
```
// Simple cases
Math.pow(7, 2); // 49
Math.pow(7, 3); // 343
Math.pow(2, 10); // 1024
// Fractional exponents
Math.pow(4, 0.5); // 2 (square root of 4)
Math.pow(8, 1 / 3); // 2 (cube root of 8)
Math.pow(2, 0.5); // 1.4142135623730951 (square root of 2)
Math.pow(2, 1 / 3); // 1.2599210498948732 (cube root of 2)
// Signed exponents
Math.pow(7, -2); // 0.02040816326530612 (1/49)
Math.pow(8, -1 / 3); // 0.5
// Signed bases
Math.pow(-7, 2); // 49 (squares are positive)
Math.pow(-7, 3); // -343 (cubes can be negative)
Math.pow(-7, 0.5); // NaN (negative numbers don't have a real square root)
// Due to "even" and "odd" roots laying close to each other,
// and limits in the floating number precision,
// negative bases with fractional exponents always return NaN,
// even when the mathematical result is real
Math.pow(-7, 1 / 3); // NaN
// Zero and infinity
Math.pow(0, 0); // 1 (anything \*\* Β±0 is 1)
Math.pow(Infinity, 0.1); // Infinity (positive exponent)
Math.pow(Infinity, -1); // 0 (negative exponent)
Math.pow(-Infinity, 1); // -Infinity (positive odd integer exponent)
Math.pow(-Infinity, 1.5); // Infinity (positive exponent)
Math.pow(-Infinity, -1); // -0 (negative odd integer exponent)
Math.pow(-Infinity, -1.5); // 0 (negative exponent)
Math.pow(0, 1); // 0 (positive exponent)
Math.pow(0, -1); // Infinity (negative exponent)
Math.pow(-0, 1); // -0 (positive odd integer exponent)
Math.pow(-0, 1.5); // 0 (positive exponent)
Math.pow(-0, -1); // -Infinity (negative odd integer exponent)
Math.pow(-0, -1.5); // Infinity (negative exponent)
Math.pow(0.9, Infinity); // 0
Math.pow(1, Infinity); // NaN
Math.pow(1.1, Infinity); // Infinity
Math.pow(0.9, -Infinity); // Infinity
Math.pow(1, -Infinity); // NaN
Math.pow(1.1, -Infinity); // 0
// NaN: only Math.pow(NaN, 0) does not result in NaN
Math.pow(NaN, 0); // 1
Math.pow(NaN, 1); // NaN
Math.pow(1, NaN); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.pow](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.pow) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `pow` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.cbrt()`](cbrt)
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.sqrt()`](sqrt)
* [Exponentiation operator](../../operators/exponentiation)
javascript Math.exp() Math.exp()
==========
The `Math.exp()` static method returns <e> raised to the power of a number. That is
πΌπππ.ππ‘π ( π‘ ) = e x \mathtt{\operatorname{Math.exp}(x)} = \mathrm{e}^x
Try it
------
Syntax
------
```
Math.exp(x)
```
### Parameters
`x` A number.
### Return value
A nonnegative number representing ex, where e is [the base of the natural logarithm](e).
Description
-----------
Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use [`Math.expm1`](expm1) instead, and obtain a much higher-precision fractional part of the answer.
Examples
--------
### Using Math.exp()
```
Math.exp(-Infinity); // 0
Math.exp(-1); // 0.36787944117144233
Math.exp(0); // 1
Math.exp(1); // 2.718281828459045
Math.exp(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.exp](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.exp) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `exp` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.E`](e)
* [`Math.expm1()`](expm1)
* [`Math.log()`](log)
* [`Math.log10()`](log10)
* [`Math.log1p()`](log1p)
* [`Math.log2()`](log2)
* [`Math.pow()`](pow)
javascript Math.E Math.E
======
The `Math.E` property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718.
Try it
------
Value
-----
πΌπππ.π΄ = e β 2.718 \mathtt{\mi{Math.E}} = e \approx 2.718
| Property attributes of `Math.E` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.E
The following function returns e:
```
function getNapier() {
return Math.E;
}
getNapier(); // 2.718281828459045
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.e](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.e) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 |
See also
--------
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log1p()`](log1p)
| programming_docs |
javascript Math.log1p() Math.log1p()
============
The `Math.log1p()` static method returns the natural logarithm (base <e>) of `1 + x`, where `x` is the argument. That is:
β x > β 1 , πΌπππ.ππππ·π ( π‘ ) = ln ( 1 + x ) \forall x > -1,;\mathtt{\operatorname{Math.log1p}(x)} = \ln(1 + x)
Try it
------
Syntax
------
```
Math.log1p(x)
```
### Parameters
`x` A number greater than or equal to -1.
### Return value
The natural logarithm (base <e>) of `x + 1`. If `x` is -1, returns [`-Infinity`](../number/negative_infinity). If `x < -1`, returns [`NaN`](../nan).
Description
-----------
For very small values of *x*, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.
When you calculate log(1 + *x*) where *x* is a small positive number, you should get an answer very close to *x*, because lim x β 0 log β‘ ( 1 + x ) x = 1 \lim\_{x \to 0} \frac{\log(1+x)}{x} = 1 . If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022β¦e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case).
If the value of `x` is less than -1, the return value is always [`NaN`](../nan).
Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.log1p()
```
Math.log1p(-2); // NaN
Math.log1p(-1); // -Infinity
Math.log1p(-0); // -0
Math.log1p(0); // 0
Math.log1p(1); // 0.6931471805599453
Math.log1p(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.log1p](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.log1p) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `log1p` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.log1p` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.expm1()`](expm1)
* [`Math.log10()`](log10)
* [`Math.log2()`](log2)
* [`Math.pow()`](pow)
javascript Math.ceil() Math.ceil()
===========
The `Math.ceil()` static method always rounds up and returns the smaller integer greater than or equal to a given number.
Try it
------
Syntax
------
```
Math.ceil(x)
```
### Parameters
`x` A number.
### Return value
The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](floor).
Description
-----------
Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.ceil()
```
Math.ceil(-Infinity); // -Infinity
Math.ceil(-7.004); // -7
Math.ceil(-4); // -4
Math.ceil(-0.95); // -0
Math.ceil(-0); // -0
Math.ceil(0); // 0
Math.ceil(0.95); // 1
Math.ceil(4); // 4
Math.ceil(7.004); // 8
Math.ceil(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.ceil](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.ceil) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `ceil` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.abs()`](abs)
* [`Math.floor()`](floor)
* [`Math.round()`](round)
* [`Math.sign()`](sign)
* [`Math.trunc()`](trunc)
javascript Math.hypot() Math.hypot()
============
The `Math.hypot()` static method returns the square root of the sum of squares of its arguments. That is,
πΌπππ.ππ’πππ ( v 1 , v 2 , β¦ , v n ) = β i = 1 n v i 2 = v 1 2 + v 2 2 + β¦ + v n 2 \mathtt{\operatorname{Math.hypot}(v\_1, v\_2, \dots, v\_n)} = \sqrt{\sum\_{i=1}^n v\_i^2} = \sqrt{v\_1^2 + v\_2^2 + \dots + v\_n^2}
Try it
------
Syntax
------
```
Math.hypot()
Math.hypot(value0)
Math.hypot(value0, value1)
Math.hypot(value0, value1, /\* β¦ ,\*/ valueN)
```
### Parameters
`value1`, β¦, `valueN`
Numbers.
### Return value
The square root of the sum of squares of the given arguments. Returns [`Infinity`](../infinity) if any of the arguments is Β±Infinity. Otherwise, if at least one of the arguments is or is converted to [`NaN`](../nan), returns [`NaN`](../nan). Returns `0` if no arguments are given or all arguments are Β±0.
Description
-----------
Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`.
This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* β¦ ,*/, vN)`.
`Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../number/max_value), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`.
With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](abs). [`Math.hypot.length`](../function/length) is 2, which weakly signals that it's designed to handle at least two parameters.
Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.hypot()
```
Math.hypot(3, 4); // 5
Math.hypot(3, 4, 5); // 7.0710678118654755
Math.hypot(); // 0
Math.hypot(NaN); // NaN
Math.hypot(NaN, Infinity); // Infinity
Math.hypot(3, 4, "foo"); // NaN, since +'foo' => NaN
Math.hypot(3, 4, "5"); // 7.0710678118654755, +'5' => 5
Math.hypot(-3); // 3, the same as Math.abs(-3)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.hypot](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.hypot) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `hypot` | 38 | 12 | 27 | No | 25 | 8 | 38 | 38 | 27 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.hypot` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.abs()`](abs)
* [`Math.pow()`](pow)
* [`Math.sqrt()`](sqrt)
javascript Math.random() Math.random()
=============
The `Math.random()` static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range β which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
Try it
------
**Note:** `Math.random()` *does not* provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the [`window.crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) method.
Syntax
------
```
Math.random()
```
### Return value
A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
Examples
--------
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for `Math.random()` itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in *extremely* rare cases to reach the usually-excluded upper bound.
### Getting a random number between 0 (inclusive) and 1 (exclusive)
```
function getRandom() {
return Math.random();
}
```
### Getting a random number between two values
This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) `min`, and is less than (and not equal) `max`.
```
function getRandomArbitrary(min, max) {
return Math.random() \* (max - min) + min;
}
```
### Getting a random integer between two values
This example returns a random *integer* between the specified values. The value is no lower than `min` (or the next integer greater than `min` if `min` isn't an integer), and is less than (but not equal to) `max`.
```
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() \* (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}
```
**Note:** It might be tempting to use [`Math.round()`](round) to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.
### Getting a random integer between two values, inclusive
While the `getRandomInt()` function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The `getRandomIntInclusive()` function below accomplishes that.
```
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() \* (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.random](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.random) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `random` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`window.crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
javascript Math.sinh() Math.sinh()
===========
The `Math.sinh()` static method returns the hyperbolic sine of a number. That is,
πΌπππ.ππππ ( π‘ ) = sinh ( x ) = e x β e β x 2 \mathtt{\operatorname{Math.sinh}(x)} = \sinh(x) = \frac{\mathrm{e}^x - \mathrm{e}^{-x}}{2}
Try it
------
Syntax
------
```
Math.sinh(x)
```
### Parameters
`x` A number.
### Return value
The hyperbolic sine of `x`.
Description
-----------
Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.sinh()
```
Math.sinh(-Infinity); // -Infinity
Math.sinh(-0); // -0
Math.sinh(0); // 0
Math.sinh(1); // 1.1752011936438014
Math.sinh(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.sinh](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sinh) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sinh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.sinh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.acosh()`](acosh)
* [`Math.asinh()`](asinh)
* [`Math.atanh()`](atanh)
* [`Math.cosh()`](cosh)
* [`Math.tanh()`](tanh)
javascript Math.max() Math.max()
==========
The `Math.max()` static method returns the largest of the numbers given as input parameters, or -[`Infinity`](../infinity) if there are no parameters.
Try it
------
Syntax
------
```
Math.max()
Math.max(value0)
Math.max(value0, value1)
Math.max(value0, value1, /\* β¦ ,\*/ valueN)
```
### Parameters
`value1`, `value2`, β¦ , `valueN`
Zero or more numbers among which the largest value will be selected and returned.
### Return value
The largest of the given numbers. Returns [`NaN`](../nan) if any of the parameters is or is converted into `NaN`. Returns -[`Infinity`](../infinity) if no parameters are provided.
Description
-----------
Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
[`Math.max.length`](../function/length) is 2, which weakly signals that it's designed to handle at least two parameters.
Examples
--------
### Using Math.max()
```
Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20
```
### Getting the maximum element of an array
[`Array.prototype.reduce()`](../array/reduce) can be used to find the maximum element in a numeric array, by comparing each value:
```
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
```
The following function uses [`Function.prototype.apply()`](../function/apply) to get the maximum of an array. `getMaxOfArray([1, 2, 3])` is equivalent to `Math.max(1, 2, 3)`, but you can use `getMaxOfArray()` on programmatically constructed arrays. This should only be used for arrays with relatively few elements.
```
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
```
The [spread syntax](../../operators/spread_syntax) is a shorter way of writing the `apply` solution to get the maximum of an array:
```
const arr = [1, 2, 3];
const max = Math.max(...arr);
```
However, both spread (`...`) and `apply` will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See [Using apply and built-in functions](../function/apply#using_apply_and_built-in_functions) for more details. The `reduce` solution does not have this problem.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.max](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.max) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `max` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.min()`](min)
javascript Math.acosh() Math.acosh()
============
The `Math.acosh()` static method returns the inverse hyperbolic cosine of a number. That is,
β x β₯ 1 , πΌπππ.πππππ ( π‘ ) = arcosh ( x ) = the unique y β₯ 0 such that cosh ( y ) = x = ln ( x + x 2 β 1 ) \begin{aligned}\forall x \geq 1,;\mathtt{\operatorname{Math.acosh}(x)} &= \operatorname{arcosh}(x) = \text{the unique } y \geq 0 \text{ such that } \cosh(y) = x\&= \ln\left(x + \sqrt{x^2 - 1}\right)\end{aligned}
Try it
------
Syntax
------
```
Math.acosh(x)
```
### Parameters
`x` A number greater than or equal to 1.
### Return value
The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns [`NaN`](../nan).
Description
-----------
Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor).
Examples
--------
### Using Math.acosh()
```
Math.acosh(0); // NaN
Math.acosh(1); // 0
Math.acosh(2); // 1.3169578969248166
Math.acosh(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.acosh](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.acosh) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `acosh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.acosh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.asinh()`](asinh)
* [`Math.atanh()`](atanh)
* [`Math.cosh()`](cosh)
* [`Math.sinh()`](sinh)
* [`Math.tanh()`](tanh)
javascript Math.fround() Math.fround()
=============
The `Math.fround()` static method returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number.
Try it
------
Syntax
------
```
Math.fround(doubleFloat)
```
### Parameters
`doubleFloat` A number.
### Return value
The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`.
Description
-----------
JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a [`Float32Array`](../float32array). This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.
To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, [`Infinity`](../infinity) or `-Infinity` is returned.
Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.fround()
The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:
```
Math.fround(1.5); // 1.5
Math.fround(1.5) === 1.5; // true
```
However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:
```
Math.fround(1.337); // 1.3370000123977661
Math.fround(1.337) === 1.337; // false
```
2 150 2^150 is too big for a 32-bit float, so `Infinity` is returned:
```
2 \*\* 150; // 1.42724769270596e+45
Math.fround(2 \*\* 150); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.fround](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.fround) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fround` | 38 | 12 | 26 | No | 25 | 8 | 38 | 38 | 26 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.fround` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.round()`](round)
| programming_docs |
javascript Math.min() Math.min()
==========
The `Math.min()` static method returns the smallest of the numbers given as input parameters, or [`Infinity`](../infinity) if there are no parameters.
Try it
------
Syntax
------
```
Math.min()
Math.min(value0)
Math.min(value0, value1)
Math.min(value0, value1, /\* β¦ ,\*/ valueN)
```
### Parameters
`value1`, β¦, `valueN`
Zero or more numbers among which the lowest value will be selected and returned.
### Return value
The smallest of the given numbers. Returns [`NaN`](../nan) if any of the parameters is or is converted into `NaN`. Returns [`Infinity`](../infinity) if no parameters are provided.
Description
-----------
Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
[`Math.min.length`](../function/length) is 2, which weakly signals that it's designed to handle at least two parameters.
Examples
--------
### Using Math.min()
This finds the min of `x` and `y` and assigns it to `z`:
```
const x = 10;
const y = -20;
const z = Math.min(x, y); // -20
```
### Clipping a value with Math.min()
`Math.min()` is often used to clip a value so that it is always less than or equal to a boundary. For instance, this
```
let x = f(foo);
if (x > boundary) {
x = boundary;
}
```
may be written as this
```
const x = Math.min(f(foo), boundary);
```
[`Math.max()`](max) can be used in a similar way to clip a value at the other end.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.min](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.min) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `min` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.max()`](max)
javascript Math.log() Math.log()
==========
The `Math.log()` static method returns the natural logarithm (base <e>) of a number. That is
β x > 0 , πΌπππ.πππ ( π‘ ) = ln ( x ) = the unique y such that e y = x \forall x > 0,;\mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique } y \text{ such that } e^y = x
Try it
------
Syntax
------
```
Math.log(x)
```
### Parameters
`x` A number greater than or equal to 0.
### Return value
The natural logarithm (base <e>) of `x`. If `x` is Β±0, returns [`-Infinity`](../number/negative_infinity). If `x < 0`, returns [`NaN`](../nan).
Description
-----------
Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
If you need the natural log of 2 or 10, use the constants [`Math.LN2`](ln2) or [`Math.LN10`](ln10). If you need a logarithm to base 2 or 10, use [`Math.log2()`](log2) or [`Math.log10()`](log10). If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster.
Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use [`Math.log1p`](log1p) instead.
Examples
--------
### Using Math.log()
```
Math.log(-1); // NaN
Math.log(-0); // -Infinity
Math.log(0); // -Infinity
Math.log(1); // 0
Math.log(10); // 2.302585092994046
Math.log(Infinity); // Infinity
```
### Using Math.log() with a different base
The following function returns the logarithm of `y` with base `x` (i.e. log x y \log\_x y ):
```
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
```
If you run `getBaseLog(10, 1000)`, it returns `2.9999999999999996` due to floating-point rounding, but still very close to the actual answer of 3.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.log](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.log) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `log` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.exp()`](exp)
* [`Math.log1p()`](log1p)
* [`Math.log10()`](log10)
* [`Math.log2()`](log2)
* [`Math.pow()`](pow)
javascript Math.expm1() Math.expm1()
============
The `Math.expm1()` static method returns <e> raised to the power of a number, subtracted by 1. That is
πΌπππ.ππ‘πππ· ( π‘ ) = e x β 1 \mathtt{\operatorname{Math.expm1}(x)} = \mathrm{e}^x - 1
Try it
------
Syntax
------
```
Math.expm1(x)
```
### Parameters
`x` A number.
### Return value
A number representing ex - 1, where e is [the base of the natural logarithm](e).
Description
-----------
For very small values of *x*, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.
When you calculate e x \mathrm{e}^x where x is a number very close to 0, you should get an answer very close to 1 + x, because lim x β 0 e x β 1 x = 1 \lim\_{x \to 0} \frac{\mathrm{e}^x - 1}{x} = 1 . If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision.
Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.expm1()
```
Math.expm1(-Infinity); // -1
Math.expm1(-1); // -0.6321205588285577
Math.expm1(-0); // -0
Math.expm1(0); // 0
Math.expm1(1); // 1.718281828459045
Math.expm1(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.expm1](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.expm1) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `expm1` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.expm1` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.E`](e)
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log10()`](log10)
* [`Math.log1p()`](log1p)
* [`Math.log2()`](log2)
* [`Math.pow()`](pow)
javascript Math.abs() Math.abs()
==========
The `Math.abs()` static method returns the absolute value of a number.
Try it
------
Syntax
------
```
Math.abs(x)
```
### Parameters
`x` A number.
### Return value
The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`.
Description
-----------
Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.abs()
```
Math.abs(-Infinity); // Infinity
Math.abs(-1); // 1
Math.abs(-0); // 0
Math.abs(0); // 0
Math.abs(1); // 1
Math.abs(Infinity); // Infinity
```
### Coercion of parameter
`Math.abs()` [coerces its parameter to a number](../number#number_coercion). Non-coercible values will become `NaN`, making `Math.abs()` also return `NaN`.
```
Math.abs("-1"); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(""); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1, 2]); // NaN
Math.abs({}); // NaN
Math.abs("string"); // NaN
Math.abs(); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.abs](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.abs) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `abs` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.ceil()`](ceil)
* [`Math.floor()`](floor)
* [`Math.round()`](round)
* [`Math.sign()`](sign)
* [`Math.trunc()`](trunc)
javascript Math.SQRT1_2 Math.SQRT1\_2
=============
The `Math.SQRT1_2` property represents the square root of 1/2, which is approximately 0.707.
Try it
------
Value
-----
πΌπππ.πππππ·\_πΈ = 1 2 β 0.707 \mathtt{\mi{Math.SQRT1\_2}} = \sqrt{\frac{1}{2}} \approx 0.707
| Property attributes of `Math.SQRT1_2` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](sqrt).
Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.SQRT1\_2
The following function returns 1 over the square root of 2:
```
function getRoot1\_2() {
return Math.SQRT1\_2;
}
getRoot1\_2(); // 0.7071067811865476
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.sqrt1\_2](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sqrt1_2) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `SQRT1_2` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.pow()`](pow)
* [`Math.sqrt()`](sqrt)
javascript Math.log10() Math.log10()
============
The `Math.log10()` static method returns the base 10 logarithm of a number. That is
β x > 0 , πΌπππ.ππππ·πΆ ( π‘ ) = log 10 ( x ) = the unique y such that 10 y = x \forall x > 0,;\mathtt{\operatorname{Math.log10}(x)} = \log\_{10}(x) = \text{the unique } y \text{ such that } 10^y = x
Try it
------
Syntax
------
```
Math.log10(x)
```
### Parameters
`x` A number greater than or equal to 0.
### Return value
The base 10 logarithm of `x`. If `x < 0`, returns [`NaN`](../nan).
Description
-----------
Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant [`Math.LOG10E`](log10e), which is 1 / [`Math.LN10`](ln10).
Examples
--------
### Using Math.log10()
```
Math.log10(-2); // NaN
Math.log10(-0); // -Infinity
Math.log10(0); // -Infinity
Math.log10(1); // 0
Math.log10(2); // 0.3010299956639812
Math.log10(100000); // 5
Math.log10(Infinity); // Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.log10](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.log10) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `log10` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.log10` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log1p()`](log1p)
* [`Math.log2()`](log2)
* [`Math.pow()`](pow)
javascript Math.atan2() Math.atan2()
============
The `Math.atan2()` static method returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`.
Try it
------
Syntax
------
```
Math.atan2(y, x)
```
### Parameters
`y` The y coordinate of the point.
`x` The x coordinate of the point.
### Return value
The angle in radians (between -Ο and Ο, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y).
Description
-----------
The `Math.atan2()` method measures the counterclockwise angle ΞΈ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.
`Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](atan) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases:
| `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` |
| --- | --- | --- | --- |
| `Infinity` | `Infinity` | Ο / 4 | `NaN` |
| `Infinity` | `-Infinity` | -Ο / 4 | `NaN` |
| `-Infinity` | `Infinity` | 3Ο / 4 | `NaN` |
| `-Infinity` | `-Infinity` | -3Ο / 4 | `NaN` |
| 0 | 0 | 0 | `NaN` |
| 0 | -0 | -0 | `NaN` |
| < 0 (including `-0`) | 0 | Ο | 0 |
| < 0 (including `-0`) | -0 | -Ο | 0 |
| `-Infinity` | > 0 | Ο | -0 |
| -0 | > 0 | Ο / 2 | -Ο / 2 |
| `-Infinity` | < 0 | -Ο | 0 |
| -0 | < 0 | -Ο / 2 | Ο / 2 |
In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than - Ο 2 -\frac{\pi}{2} or greater than Ο 2 \frac{\pi}{2} .
Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.atan2()
```
Math.atan2(90, 15); // 1.4056476493802699
Math.atan2(15, 90); // 0.16514867741462683
```
### Difference between Math.atan2(y, x) and Math.atan(y / x)
The following script prints all inputs that produce a difference between `Math.atan2(y, x)` and `Math.atan(y / x)`.
```
const formattedNumbers = new Map([
[-Math.PI, "-Ο"],
[(-3 \* Math.PI) / 4, "-3Ο/4"],
[-Math.PI / 2, "-Ο/2"],
[-Math.PI / 4, "-Ο/4"],
[Math.PI / 4, "Ο/4"],
[Math.PI / 2, "Ο/2"],
[(3 \* Math.PI) / 4, "3Ο/4"],
[Math.PI, "Ο"],
[-Infinity, "-β"],
[Infinity, "β"],
]);
function format(template, ...args) {
return String.raw(
{ raw: template },
...args.map((num) =>
(Object.is(num, -0)
? "-0"
: formattedNumbers.get(num) ?? String(num)
).padEnd(5)
)
);
}
console.log(`| x | y | atan2 | atan |
|-------|-------|-------|-------|`);
for (const x of [-Infinity, -1, -0, 0, 1, Infinity]) {
for (const y of [-Infinity, -1, -0, 0, 1, Infinity]) {
const atan2 = Math.atan2(y, x);
const atan = Math.atan(y / x);
if (!Object.is(atan2, atan)) {
console.log(format`| ${x} | ${y} | ${atan2} | ${atan} |`);
}
}
}
```
The output is:
```
| x | y | atan2 | atan |
|-------|-------|-------|-------|
| -β | -β | -3Ο/4 | NaN |
| -β | -1 | -Ο | 0 |
| -β | -0 | -Ο | 0 |
| -β | 0 | Ο | -0 |
| -β | 1 | Ο | -0 |
| -β | β | 3Ο/4 | NaN |
| -1 | -β | -Ο/2 | Ο/2 |
| -1 | -1 | -3Ο/4 | Ο/4 |
| -1 | -0 | -Ο | 0 |
| -1 | 0 | Ο | -0 |
| -1 | 1 | 3Ο/4 | -Ο/4 |
| -1 | β | Ο/2 | -Ο/2 |
| -0 | -β | -Ο/2 | Ο/2 |
| -0 | -1 | -Ο/2 | Ο/2 |
| -0 | -0 | -Ο | NaN |
| -0 | 0 | Ο | NaN |
| -0 | 1 | Ο/2 | -Ο/2 |
| -0 | β | Ο/2 | -Ο/2 |
| 0 | -0 | -0 | NaN |
| 0 | 0 | 0 | NaN |
| β | -β | -Ο/4 | NaN |
| β | β | Ο/4 | NaN |
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.atan2](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.atan2) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `atan2` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.acos()`](acos)
* [`Math.asin()`](asin)
* [`Math.atan()`](atan)
* [`Math.cos()`](cos)
* [`Math.sin()`](sin)
* [`Math.tan()`](tan)
javascript Math.acos() Math.acos()
===========
The `Math.acos()` static method returns the inverse cosine (in radians) of a number. That is,
β x β [ β 1 , 1 ] , πΌπππ.ππππ ( π‘ ) = arccos ( x ) = the unique y β [ 0 , Ο ] such that cos ( y ) = x \forall x \in [{-1}, 1],;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{the unique } y \in [0, \pi] \text{ such that } \cos(y) = x
Try it
------
Syntax
------
```
Math.acos(x)
```
### Parameters
`x` A number between -1 and 1, inclusive, representing the angle's cosine value.
### Return value
The inverse cosine (angle in radians between 0 and Ο, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns [`NaN`](../nan).
Description
-----------
Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.acos()
```
Math.acos(-2); // NaN
Math.acos(-1); // 3.141592653589793 (Ο)
Math.acos(0); // 1.5707963267948966 (Ο/2)
Math.acos(0.5); // 1.0471975511965979 (Ο/3)
Math.acos(1); // 0
Math.acos(2); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.acos](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.acos) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `acos` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.asin()`](asin)
* [`Math.atan()`](atan)
* [`Math.atan2()`](atan2)
* [`Math.cos()`](cos)
* [`Math.sin()`](sin)
* [`Math.tan()`](tan)
javascript Math.imul() Math.imul()
===========
The `Math.imul()` static method returns the result of the C-like 32-bit multiplication of the two parameters.
Try it
------
Syntax
------
```
Math.imul(a, b)
```
### Parameters
`a` First number.
`b` Second number.
### Return value
The result of the C-like 32-bit multiplication of the given arguments.
Description
-----------
`Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten).
Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. However, with [asm.js](https://developer.mozilla.org/en-US/docs/Games/Tools/asm.js), which allows JIT-optimizers to more confidently use integers in JavaScript, multiplying two numbers stored internally as integers (which is only possible with asm.js) with `imul()` could be potentially more performant.
Examples
--------
### Using Math.imul()
```
Math.imul(2, 4); // 8
Math.imul(-1, 8); // -8
Math.imul(-2, -2); // 4
Math.imul(0xffffffff, 5); // -5
Math.imul(0xfffffffe, 5); // -10
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.imul](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.imul) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `imul` | 28 | 12 | 20 | No | 16 | 7 | 4.4 | 28 | 20 | 15 | 7 | 1.5 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.imul` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [Emscripten](https://en.wikipedia.org/wiki/Emscripten)
| programming_docs |
javascript Math.floor() Math.floor()
============
The `Math.floor()` static method always rounds down and returns the largest integer less than or equal to a given number.
Try it
------
Syntax
------
```
Math.floor(x)
```
### Parameters
`x` A number.
### Return value
The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](ceil).
Description
-----------
Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.floor()
```
Math.floor(-Infinity); // -Infinity
Math.floor(-45.95); // -46
Math.floor(-45.05); // -46
Math.floor(-0); // -0
Math.floor(0); // 0
Math.floor(4); // 4
Math.floor(45.05); // 45
Math.floor(45.95); // 45
Math.floor(Infinity); // Infinity
```
### Decimal adjustment
In this example, we implement a method called `decimalAdjust()` that is an enhancement method of `Math.floor()`, [`Math.ceil()`](ceil), and [`Math.round()`](round). While the three `Math` functions always adjust the input to the units digit, `decimalAdjust` accepts an `exp` parameter that specifies the number of digits to the left of the decimal point to which the number should be adjusted. For example, `-1` means it would leave one digit after the decimal point (as in "Γ 10-1"). In addition, it allows you to select the means of adjustment β `round`, `floor`, or `ceil` β through the `type` parameter.
It does so by multiplying the number by a power of 10, then rounding the result to the nearest integer, then dividing by the power of 10. To better preserve precision, it takes advantage of Number's [`toString()`](../number/tostring) method, which represents large or small numbers in scientific notation (like `6.02e23`).
```
/\*\*
\* Adjusts a number to the specified digit.
\*
\* @param {"round" | "floor" | "ceil"} type The type of adjustment.
\* @param {number} value The number.
\* @param {number} exp The exponent (the 10 logarithm of the adjustment base).
\* @returns {number} The adjusted value.
\*/
function decimalAdjust(type, value, exp) {
type = String(type);
if (!["round", "floor", "ceil"].includes(type)) {
throw new TypeError(
"The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'."
);
}
exp = Number(exp);
value = Number(value);
if (exp % 1 !== 0 || Number.isNaN(value)) {
return NaN;
} else if (exp === 0) {
return Math[type](value);
}
const [magnitude, exponent = 0] = value.toString().split("e");
const adjustedValue = Math[type](`${magnitude}e${exponent - exp}`);
// Shift back
const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e");
return Number(`${newMagnitude}e${+newExponent + exp}`);
}
// Decimal round
const round10 = (value, exp) => decimalAdjust("round", value, exp);
// Decimal floor
const floor10 = (value, exp) => decimalAdjust("floor", value, exp);
// Decimal ceil
const ceil10 = (value, exp) => decimalAdjust("ceil", value, exp);
// Round
round10(55.55, -1); // 55.6
round10(55.549, -1); // 55.5
round10(55, 1); // 60
round10(54.9, 1); // 50
round10(-55.55, -1); // -55.5
round10(-55.551, -1); // -55.6
round10(-55, 1); // -50
round10(-55.1, 1); // -60
// Floor
floor10(55.59, -1); // 55.5
floor10(59, 1); // 50
floor10(-55.51, -1); // -55.6
floor10(-51, 1); // -60
// Ceil
ceil10(55.51, -1); // 55.6
ceil10(51, 1); // 60
ceil10(-55.59, -1); // -55.5
ceil10(-59, 1); // -50
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.floor](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.floor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `floor` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.abs()`](abs)
* [`Math.ceil()`](ceil)
* [`Math.round()`](round)
* [`Math.sign()`](sign)
* [`Math.trunc()`](trunc)
javascript Math.LN10 Math.LN10
=========
The `Math.LN10` property represents the natural logarithm of 10, approximately 2.302.
Try it
------
Value
-----
πΌπππ.π»π½π·πΆ = ln ( 10 ) β 2.302 \mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302
| Property attributes of `Math.LN10` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.LN10
The following function returns the natural log of 10:
```
function getNatLog10() {
return Math.LN10;
}
getNatLog10(); // 2.302585092994046
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.ln10](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.ln10) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `LN10` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.exp()`](exp)
* [`Math.log()`](log)
* [`Math.log10()`](log10)
javascript Math.atanh() Math.atanh()
============
The `Math.atanh()` static method returns the inverse hyperbolic tangent of a number. That is,
β x β ( β 1 , 1 ) , πΌπππ.πππππ ( π‘ ) = artanh ( x ) = the unique y such that tanh ( y ) = x = 1 2 ln ( 1 + x 1 β x ) \begin{aligned}\forall x \in ({-1}, 1),;\mathtt{\operatorname{Math.atanh}(x)} &= \operatorname{artanh}(x) = \text{the unique } y \text{ such that } \tanh(y) = x \&= \frac{1}{2},\ln\left(\frac{1+x}{1-x}\right)\end{aligned}
Try it
------
Syntax
------
```
Math.atanh(x)
```
### Parameters
`x` A number between -1 and 1, inclusive.
### Return value
The inverse hyperbolic tangent of `x`. If `x` is 1, returns [`Infinity`](../infinity). If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns [`NaN`](../nan).
Description
-----------
Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.atanh()
```
Math.atanh(-2); // NaN
Math.atanh(-1); // -Infinity
Math.atanh(-0); // -0
Math.atanh(0); // 0
Math.atanh(0.5); // 0.5493061443340548
Math.atanh(1); // Infinity
Math.atanh(2); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.atanh](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.atanh) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `atanh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Math.atanh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
* [`Math.acosh()`](acosh)
* [`Math.asinh()`](asinh)
* [`Math.cosh()`](cosh)
* [`Math.sinh()`](sinh)
* [`Math.tanh()`](tanh)
javascript Math.sin() Math.sin()
==========
The `Math.sin()` static method returns the sine of a number in radians.
Try it
------
Syntax
------
```
Math.sin(x)
```
### Parameters
`x` A number representing an angle in radians.
### Return value
The sine of `x`, between -1 and 1, inclusive. If `x` is [`Infinity`](../infinity), `-Infinity`, or [`NaN`](../nan), returns [`NaN`](../nan).
Description
-----------
Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.sin()
```
Math.sin(-Infinity); // NaN
Math.sin(-0); // -0
Math.sin(0); // 0
Math.sin(1); // 0.8414709848078965
Math.sin(Math.PI / 2); // 1
Math.sin(Infinity); // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.sin](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sin) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sin` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.acos()`](acos)
* [`Math.asin()`](asin)
* [`Math.atan()`](atan)
* [`Math.atan2()`](atan2)
* [`Math.cos()`](cos)
* [`Math.tan()`](tan)
javascript Math.tan() Math.tan()
==========
The `Math.tan()` static method returns the tangent of a number in radians.
Try it
------
Syntax
------
```
Math.tan(x)
```
### Parameters
`x` A number representing an angle in radians.
### Return value
The tangent of `x`. If `x` is [`Infinity`](../infinity), `-Infinity`, or [`NaN`](../nan), returns [`NaN`](../nan).
**Note:** Due to floating point precision, it's not possible to obtain the exact value Ο/2, so the result is always finite if not `NaN`.
Description
-----------
Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.tan()
```
Math.tan(-Infinity); // NaN
Math.tan(-0); // -0
Math.tan(0); // 0
Math.tan(1); // 1.5574077246549023
Math.tan(Math.PI / 4); // 0.9999999999999999 (Floating point error)
Math.tan(Infinity); // NaN
```
### Math.tan() and Ο/2
It's not possible to calculate `tan(Ο/2)` exactly.
```
Math.tan(Math.PI / 2); // 16331239353195370
Math.tan(Math.PI / 2 + Number.EPSILON); // -6218431163823738
```
### Using Math.tan() with a degree value
Because the `Math.tan()` function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent.
```
function getTanDeg(deg) {
const rad = (deg \* Math.PI) / 180;
return Math.tan(rad);
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.tan](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.tan) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `tan` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.acos()`](acos)
* [`Math.asin()`](asin)
* [`Math.atan()`](atan)
* [`Math.atan2()`](atan2)
* [`Math.cos()`](cos)
* [`Math.sin()`](sin)
javascript Math.SQRT2 Math.SQRT2
==========
The `Math.SQRT2` property represents the square root of 2, approximately 1.414.
Try it
------
Value
-----
πΌπππ.πππππΈ = 2 β 1.414 \mathtt{\mi{Math.SQRT2}} = \sqrt{2} \approx 1.414
| Property attributes of `Math.SQRT2` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](sqrt).
Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
Examples
--------
### Using Math.SQRT2
The following function returns the square root of 2:
```
function getRoot2() {
return Math.SQRT2;
}
getRoot2(); // 1.4142135623730951
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math.sqrt2](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sqrt2) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `SQRT2` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Math.pow()`](pow)
* [`Math.sqrt()`](sqrt)
javascript WeakRef() constructor WeakRef() constructor
=====================
The `WeakRef` constructor creates a [`WeakRef`](../weakref) object referring to a given target object.
Syntax
------
```
new WeakRef(targetObject)
```
**Note:** `WeakRef()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`targetObject` The target object the WeakRef should refer to (also called the *referent*).
Examples
--------
### Creating a new WeakRef object
See the main [`WeakRef`](../weakref#examples) page for a complete example.
```
class Counter {
constructor(element) {
// Remember a weak reference to a DOM element
this.ref = new WeakRef(element);
this.start();
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weak-ref-constructor](https://tc39.es/ecma262/multipage/managing-memory.html#sec-weak-ref-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 |
| `WeakRef` | 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)
javascript WeakRef.prototype.deref() WeakRef.prototype.deref()
=========================
The `deref` method returns the [`WeakRef`](../weakref) instance's target object, or `undefined` if the target object has been garbage-collected.
Syntax
------
```
deref()
```
### Return value
The target object of the WeakRef, or `undefined` if the object has been garbage-collected.
Description
-----------
See the [Notes on WeakRefs](../weakref#notes_on_weakrefs) section of the [`WeakRef`](../weakref) page for some important notes.
Examples
--------
### Using deref
See the [Examples](../weakref#examples) section of the [`WeakRef`](../weakref) page for the complete example.
```
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;
}
};
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weak-ref.prototype.deref](https://tc39.es/ecma262/multipage/managing-memory.html#sec-weak-ref.prototype.deref) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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
--------
* [`WeakRef`](../weakref)
javascript Number.parseFloat() Number.parseFloat()
===================
The `Number.parseFloat()` static method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../nan).
Try it
------
Syntax
------
```
Number.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.
Examples
--------
### Number.parseFloat vs parseFloat
This method has the same functionality as the global [`parseFloat()`](../parsefloat) function:
```
Number.parseFloat === parseFloat; // true
```
Its purpose is modularization of globals.
See [`parseFloat()`](../parsefloat) for more detail and examples.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.parsefloat](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.parsefloat) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 34 | 12 | 25 | No | 21 | 9 | 37 | 34 | 25 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Number.parseFloat` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* [`Number`](../number): The object this method belongs to.
* The global [`parseFloat()`](../parsefloat) method.
javascript Number.NEGATIVE_INFINITY Number.NEGATIVE\_INFINITY
=========================
The `Number.NEGATIVE_INFINITY` property represents the negative Infinity value.
Try it
------
Value
-----
The same as the negative value of the global [`Infinity`](../infinity) property.
| Property attributes of `Number.NEGATIVE_INFINITY` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity:
* Any positive value, including [`POSITIVE_INFINITY`](positive_infinity), multiplied by `NEGATIVE_INFINITY` is `NEGATIVE_INFINITY`.
* Any negative value, including `NEGATIVE_INFINITY`, multiplied by `NEGATIVE_INFINITY` is [`POSITIVE_INFINITY`](positive_infinity).
* Any positive value divided by `NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)).
* Any negative value divided by `NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)).
* Zero multiplied by `NEGATIVE_INFINITY` is [`NaN`](../nan).
* [`NaN`](../nan) multiplied by `NEGATIVE_INFINITY` is [`NaN`](../nan).
* `NEGATIVE_INFINITY`, divided by any negative value except `NEGATIVE_INFINITY`, is [`POSITIVE_INFINITY`](positive_infinity).
* `NEGATIVE_INFINITY`, divided by any positive value except [`POSITIVE_INFINITY`](positive_infinity), is `NEGATIVE_INFINITY`.
* `NEGATIVE_INFINITY`, divided by either `NEGATIVE_INFINITY` or [`POSITIVE_INFINITY`](positive_infinity), is [`NaN`](../nan).
* `x > Number.NEGATIVE_INFINITY` is true for any number *x* that isn't `NEGATIVE_INFINITY`.
You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../nan) would be more appropriate in such a case.
Because `NEGATIVE_INFINITY` is a static property of [`Number`](../number), you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value.
Examples
--------
### Using NEGATIVE\_INFINITY
In the following example, the variable `smallNumber` is assigned a value that is smaller than the minimum value. When the [`if`](../../statements/if...else) statement executes, `smallNumber` has the value `-Infinity`, so `smallNumber` is set to a more manageable value before continuing.
```
let smallNumber = -Number.MAX\_VALUE \* 2;
if (smallNumber === Number.NEGATIVE\_INFINITY) {
smallNumber = returnFinite();
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.negative\_infinity](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.negative_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 |
| `NEGATIVE_INFINITY` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.POSITIVE_INFINITY`](positive_infinity)
* [`Number.isFinite()`](isfinite)
* [`Infinity`](../infinity)
* [`isFinite()`](../isfinite)
| programming_docs |
javascript Number.prototype.toLocaleString() Number.prototype.toLocaleString()
=================================
The `toLocaleString()` method returns a string with a language-sensitive representation of this number. 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 number.
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) property.
Examples
--------
### Using toLocaleString()
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(number.toLocaleString()); // "3,500" if in U.S. English locale
```
### Checking for support for locales and options arguments
Not all implementations are required to support ECMA-402 (the Internationalization API). For those that don't, the `locales` and `options` arguments must both be ignored. You can check support by testing if illegal language tags are rejected with a [`RangeError`](../rangeerror):
```
function toLocaleStringSupportsLocales() {
const number = 0;
try {
number.toLocaleString('i');
} catch (e) {
return e.name === 'RangeError';
}
return false;
}
```
However, prior to ES5.1, implementations were not required to throw a range error exception if `toLocaleString` is called with illegal arguments. A check that works in all hosts, including those supporting ECMA-262 prior to ed 5.1, is to test for the features specified in ECMA-402 that are required to support regional options for `Number.prototype.toLocaleString` directly:
```
function toLocaleStringSupportsOptions() {
return !!(typeof Intl === 'object' && Intl && typeof Intl.NumberFormat === 'function');
}
```
This tests for a global `Intl` object, checks that it's not `null` and that it has a `NumberFormat` property that is a function.
### 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(number.toLocaleString('de-DE'));
// β 123.456,789
// Arabic in most Arabic speaking countries uses Eastern Arabic digits
console.log(number.toLocaleString('ar-EG'));
// β Ω‘Ω’Ω£Ω€Ω₯Ω¦Ω«Ω§Ω¨Ω©
// India uses thousands/lakh/crore separators
console.log(number.toLocaleString('en-IN'));
// β 1,23,456.789
// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(number.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(number.toLocaleString(['ban', 'id']));
// β 123.456,789
```
### Using options
The results provided by `toLocaleString` can be customized using the `options` parameter:
```
const number = 123456.789;
// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// β 123.456,79 β¬
// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// β οΏ₯123,457
// limit to three significant digits
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// β 1,23,000
// Use the host default language with options for number formatting
const num = 30000.65;
console.log(num.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
// β "30,000.65" where English is the default language, or
// β "30.000,65" where German is the default language, or
// β "30 000,65" where French is the default language
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.prototype.tolocalestring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.tolocalestring) |
| [ECMAScript Internationalization API Specification # sup-number.prototype.tolocalestring](https://tc39.es/ecma402/#sup-number.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
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 |
| `locales` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 26 | 56 | 14 | 10 | 1.5 | 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` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 26 | 56 | 14 | 10 | 1.5 | 1.0 | 0.12.0 |
See also
--------
* [`Number.prototype.toString()`](tostring)
javascript Number.MAX_SAFE_INTEGER Number.MAX\_SAFE\_INTEGER
=========================
The `Number.MAX_SAFE_INTEGER` constant represents the maximum safe integer in JavaScript (253 β 1).
For larger integers, consider using [`BigInt`](../bigint).
Try it
------
Value
-----
`9007199254740991` (9,007,199,254,740,991, or ~9 quadrillion).
| Property attributes of `Number.MAX_SAFE_INTEGER` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
[Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](../number#number_encoding), so it can only safely represent integers between -(253 β 1) and 253 β 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See [`Number.isSafeInteger()`](issafeinteger) for more information.
Because `MAX_SAFE_INTEGER` is a static property of [`Number`](../number), you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value.
Examples
--------
### Return value of MAX\_SAFE\_INTEGER
```
Number.MAX\_SAFE\_INTEGER; // 9007199254740991
```
### Relationship between MAX\_SAFE\_INTEGER and EPSILON
[`Number.EPSILON`](epsilon) is 2-52, while `MAX_SAFE_INTEGER` is 253 β 1 β both of them are derived from the width of the mantissa, which is 53 bits (with the highest bit always being 1). Multiplying them will give a value very close β but not equal β to 2.
```
Number.MAX\_SAFE\_INTEGER \* Number.EPSILON; // 1.9999999999999998
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.max\_safe\_integer](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.max_safe_integer) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `MAX_SAFE_INTEGER` | 34 | 12 | 31 | No | 21 | 9 | 37 | 34 | 31 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Number.MAX_SAFE_INTEGER` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* [`Number.MIN_SAFE_INTEGER`](min_safe_integer)
* [`Number.isSafeInteger()`](issafeinteger)
* [`BigInt`](../bigint)
javascript Number.MAX_VALUE Number.MAX\_VALUE
=================
The `Number.MAX_VALUE` property represents the maximum numeric value representable in JavaScript.
Try it
------
Value
-----
21024 - 1, or approximately `1.7976931348623157E+308`.
| Property attributes of `Number.MAX_VALUE` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Values larger than `MAX_VALUE` are represented as [`Infinity`](../infinity) and will lose their actual value.
Because `MAX_VALUE` is a static property of [`Number`](../number), you always use it as `Number.MAX_VALUE`, rather than as a property of a number value.
Examples
--------
### Using MAX\_VALUE
The following code multiplies two numeric values. If the result is less than or equal to `MAX_VALUE`, the `func1` function is called; otherwise, the `func2` function is called.
```
if (num1 \* num2 <= Number.MAX\_VALUE) {
func1();
} else {
func2();
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.max\_value](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.max_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 |
| `MAX_VALUE` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.MIN_VALUE`](min_value)
* The [`Number`](../number) object it belongs to
javascript Number.prototype.toFixed() Number.prototype.toFixed()
==========================
The `toFixed()` method formats a number using fixed-point notation.
Try it
------
Syntax
------
```
toFixed()
toFixed(digits)
```
### Parameters
`digits` Optional
The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`.
### Return value
A string representing the given number using fixed-point notation.
### Exceptions
[`RangeError`](../rangeerror) If `digits` is smaller than `0`, larger than `100`, or is `NaN`.
[`TypeError`](../typeerror) If this method is invoked on an object that is not a [`Number`](../number).
Description
-----------
The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.
If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](tostring) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite.
The output of `toFixed()` may be more precise than [`toString()`](tostring) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example:
```
(1000000000000000128).toString(); // '1000000000000000100'
(1000000000000000128).toFixed(0); // '1000000000000000128'
```
However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example:
```
0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180'
```
Examples
--------
### Using toFixed()
```
const numObj = 12345.6789;
numObj.toFixed(); // '12346'; rounding, no fractional part
numObj.toFixed(1); // '12345.7'; it rounds up
numObj.toFixed(6); // '12345.678900'; additional zeros
(1.23e+20).toFixed(2); // '123000000000000000000.00'
(1.23e-10).toFixed(2); // '0.00'
2.34.toFixed(1); // '2.3'
2.35.toFixed(1); // '2.4'; it rounds up
2.55.toFixed(1); // '2.5'
// it rounds down as it can't be represented exactly by a float and the
// closest representable float is lower
2.449999999999999999.toFixed(1); // '2.5'
// it rounds up as it's less than NUMBER.EPSILON away from 2.45.
// This literal actually encodes the same number value as 2.45
(6.02 \* 10 \*\* 23).toFixed(50); // 6.019999999999999e+23; large numbers still use exponential notation
```
### Using toFixed() with negative numbers
Because member access has higher [precedence](../../operators/operator_precedence) than unary minus, you need to group the negative number expression to get a string.
```
-2.34.toFixed(1); // -2.3, a number
(-2.34).toFixed(1); // '-2.3'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.prototype.tofixed](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.tofixed) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toFixed` | 1 | 12 | 1 | 5.5 | 7 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.prototype.toExponential()`](toexponential)
* [`Number.prototype.toPrecision()`](toprecision)
* [`Number.prototype.toString()`](tostring)
* [`Number.EPSILON`](epsilon)
javascript Number.isFinite() Number.isFinite()
=================
The `Number.isFinite()` static method determines whether the passed value is a finite number β that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../infinity), negative `Infinity`, nor [`NaN`](../nan).
Try it
------
Syntax
------
```
Number.isFinite(value)
```
### Parameters
`value` The value to be tested for finiteness.
### Return value
The boolean value `true` if the given value is a finite number. Otherwise `false`.
Examples
--------
### Using isFinite()
```
Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(-Infinity); // false
Number.isFinite(0); // true
Number.isFinite(2e64); // true
```
### Difference between Number.isFinite() and global isFinite()
In comparison to the global [`isFinite()`](../isfinite) function, this method doesn't first convert the parameter to a number. This means only values of the type number *and* are finite return `true`, and non-numbers always return `false`.
```
isFinite('0'); // true; coerced to number 0
Number.isFinite("0"); // false
isFinite(null); // true; coerced to number 0
Number.isFinite(null); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.isfinite](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.isfinite) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 19 | 12 | 16 | No | 15 | 9 | 4.4 | 25 | 16 | 14 | 9 | 1.5 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Number.isFinite` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* The [`Number`](../number) object it belongs to
* The global function [`isFinite`](../isfinite)
javascript Number.prototype.valueOf() Number.prototype.valueOf()
==========================
The `valueOf()` method returns the wrapped primitive value of a [`Number`](../number) object.
Try it
------
Syntax
------
```
valueOf()
```
### Return value
A number representing the primitive value of the specified [`Number`](../number) object.
Description
-----------
This method is usually called internally by JavaScript and not explicitly in web code.
Examples
--------
### Using valueOf
```
const numObj = new Number(10);
console.log(typeof numObj); // object
const num = numObj.valueOf();
console.log(num); // 10
console.log(typeof num); // number
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.prototype.valueof](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.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` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.prototype.valueOf()`](../object/valueof)
javascript Number() constructor Number() constructor
====================
The `Number()` creates a [`Number`](../number) object. When called instead as a function, it performs type conversion to a [primitive number](https://developer.mozilla.org/en-US/docs/Glossary/Number), which is usually more useful.
Syntax
------
```
new Number(value)
Number(value)
```
**Note:** `Number()` can be called with or without [`new`](../../operators/new), but with different effects. See [Return value](#return_value).
### Parameters
`value` The numeric value of the object being created.
### Return value
When `Number` is called as a constructor (with [`new`](../../operators/new)), it creates a [`Number`](../number) object, which is **not** a primitive.
When `Number` is called as a function, it [coerces the parameter to a number primitive](../number#number_coercion). [BigInts](../bigint) are converted to numbers. If the value can't be converted, it returns [`NaN`](../nan).
**Warning:** You should rarely find yourself using `Number` as a constructor.
Examples
--------
### Creating Number objects
```
const a = new Number('123'); // a === 123 is false
const b = Number('123'); // b === 123 is true
a instanceof Number; // is true
b instanceof Number; // is false
typeof a // "object"
typeof b // "number"
```
### Using Number() to convert a BigInt to a number
`Number()` is the only case where a BigInt can be converted to a number without throwing, because it's very explicit.
```
+1n; // TypeError: Cannot convert a BigInt value to a number
0 + 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
```
```
Number(1n); // 1
```
Note that this may result in loss of precision, if the BigInt is too large to be [safely represented](issafeinteger).
```
BigInt(Number(2n \*\* 54n + 1n)) === 2n \*\* 54n + 1n; // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number-constructor](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number-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 |
| `Number` | 1 | 12 | 1 | 3 | 3 | 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)
* The [`Math`](../math) global object
* Integers with arbitrary precision: [`BigInt`](../bigint)
| programming_docs |
javascript Number.prototype.toExponential() Number.prototype.toExponential()
================================
The `toExponential()` method returns a string representing the [`Number`](../number) object in exponential notation.
Try it
------
Syntax
------
```
toExponential()
toExponential(fractionDigits)
```
### Parameters
`fractionDigits` Optional
Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number.
### Return value
A string representing the given [`Number`](../number) object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point.
### Exceptions
[`RangeError`](../rangeerror) If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../rangeerror).
[`TypeError`](../typeerror) If this method is invoked on an object that is not a [`Number`](../number).
Description
-----------
If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely.
If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point.
If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`toFixed()`](tofixed) method, which also applies to `toExponential()`.
Examples
--------
### Using toExponential
```
const numObj = 77.1234;
console.log(numObj.toExponential()); // 7.71234e+1
console.log(numObj.toExponential(4)); // 7.7123e+1
console.log(numObj.toExponential(2)); // 7.71e+1
console.log(77.1234.toExponential()); // 7.71234e+1
console.log((77).toExponential()); // 7.7e+1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.prototype.toexponential](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.toexponential) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toExponential` | 1 | 12 | 1 | 5.5 | 7 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [A polyfill of `Number.prototype.toExponential`](https://github.com/zloirock/core-js#ecmascript-number) with many bug fixes is available in [`core-js`](https://github.com/zloirock/core-js)
* [`Number.prototype.toFixed()`](tofixed)
* [`Number.prototype.toPrecision()`](toprecision)
* [`Number.prototype.toString()`](tostring)
javascript Number.MIN_SAFE_INTEGER Number.MIN\_SAFE\_INTEGER
=========================
The `Number.MIN_SAFE_INTEGER` constant represents the minimum safe integer in JavaScript, or -(253 - 1).
To represent integers smaller than this, consider using [`BigInt`](../bigint).
Try it
------
Value
-----
`-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion).
| Property attributes of `Number.MIN_SAFE_INTEGER` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
[Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](../number#number_encoding), so it can only safely represent integers between -(253 β 1) and 253 β 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See [`Number.isSafeInteger()`](issafeinteger) for more information.
Because `MIN_SAFE_INTEGER` is a static property of [`Number`](../number), you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value.
Examples
--------
### Using MIN\_SAFE\_INTEGER
```
Number.MIN\_SAFE\_INTEGER; // -9007199254740991
-(2 \*\* 53 - 1); // -9007199254740991
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.min\_safe\_integer](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.min_safe_integer) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `MIN_SAFE_INTEGER` | 34 | 12 | 31 | No | 21 | 9 | 37 | 34 | 31 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Number.MIN_SAFE_INTEGER` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* [`Number.MAX_SAFE_INTEGER`](max_safe_integer)
* [`Number.isSafeInteger()`](issafeinteger)
* [`BigInt`](../bigint)
javascript Number.POSITIVE_INFINITY Number.POSITIVE\_INFINITY
=========================
The `Number.POSITIVE_INFINITY` property represents the positive Infinity value.
Try it
------
Value
-----
The same as the value of the global [`Infinity`](../infinity) property.
| Property attributes of `Number.POSITIVE_INFINITY` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity:
* Any positive value, including `POSITIVE_INFINITY`, multiplied by `POSITIVE_INFINITY` is `POSITIVE_INFINITY`.
* Any negative value, including [`NEGATIVE_INFINITY`](negative_infinity), multiplied by `POSITIVE_INFINITY` is [`NEGATIVE_INFINITY`](negative_infinity).
* Any positive number divided by `POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)).
* Any negative number divided by `POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754).
* Zero multiplied by `POSITIVE_INFINITY` is [`NaN`](../nan).
* [`NaN`](../nan) multiplied by `POSITIVE_INFINITY` is [`NaN`](../nan).
* `POSITIVE_INFINITY`, divided by any negative value except [`NEGATIVE_INFINITY`](negative_infinity), is [`NEGATIVE_INFINITY`](negative_infinity).
* `POSITIVE_INFINITY`, divided by any positive value except `POSITIVE_INFINITY`, is `POSITIVE_INFINITY`.
* `POSITIVE_INFINITY`, divided by either [`NEGATIVE_INFINITY`](negative_infinity) or `POSITIVE_INFINITY`, is [`NaN`](../nan).
* `Number.POSITIVE_INFINITY > x` is true for any number *x* that isn't `POSITIVE_INFINITY`.
You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../nan) would be more appropriate in such a case.
Because `POSITIVE_INFINITY` is a static property of [`Number`](../number), you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value.
Examples
--------
### Using POSITIVE\_INFINITY
In the following example, the variable `bigNumber` is assigned a value that is larger than the maximum value. When the [`if`](../../statements/if...else) statement executes, `bigNumber` has the value `Infinity`, so `bigNumber` is set to a more manageable value before continuing.
```
let bigNumber = Number.MAX\_VALUE \* 2;
if (bigNumber === Number.POSITIVE\_INFINITY) {
bigNumber = returnFinite();
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.positive\_infinity](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.positive_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 |
| `POSITIVE_INFINITY` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.NEGATIVE_INFINITY`](negative_infinity)
* [`Number.isFinite()`](isfinite)
* [`Infinity`](../infinity)
* [`isFinite()`](../isfinite)
javascript Number.isNaN() Number.isNaN()
==============
The `Number.isNaN()` static method determines whether the passed value is the number value [`NaN`](../nan), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global [`isNaN()`](../isnan) function.
Try it
------
Syntax
------
```
Number.isNaN(value)
```
### Parameters
`value` The value to be tested for [`NaN`](../nan).
### Return value
The boolean value `true` if the given value is a number with value [`NaN`](../nan). Otherwise, `false`.
Description
-----------
The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](../../operators/equality) or [`===`](../../operators/strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../nan), even if the other operand is also [`NaN`](../nan).
Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable.
As opposed to the global [`isNaN()`](../isnan) function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../nan) but aren't actually the same value as [`NaN`](../nan). This also means that only values of the Number type that are also [`NaN`](../nan) return `true`.
Examples
--------
### Using isNaN()
```
Number.isNaN(NaN); // true
Number.isNaN(Number.NaN); // true
Number.isNaN(0 / 0); // true
Number.isNaN(37); // false
```
### Difference between Number.isNaN() and global isNaN()
`Number.isNaN()` doesn't attempt to convert the parameter to a number, so non-numbers always return `false`. The following are all `false`:
```
Number.isNaN("NaN");
Number.isNaN(undefined);
Number.isNaN({});
Number.isNaN("blabla");
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN("37");
Number.isNaN("37.37");
Number.isNaN("");
Number.isNaN(" ");
```
The global [`isNaN()`](../isnan) coerces its parameter to a number:
```
isNaN("NaN"); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN("blabla"); // true
isNaN(true); // false, this is coerced to 1
isNaN(null); // false, this is coerced to 0
isNaN("37"); // false, this is coerced to 37
isNaN("37.37"); // false, this is coerced to 37.37
isNaN(""); // false, this is coerced to 0
isNaN(" "); // false, this is coerced to 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.isnan](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.isnan) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 25 | 12 | 15 | No | 15 | 9 | 4.4 | 25 | 15 | 14 | 9 | 1.5 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Number.isNaN` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* [`Number`](../number)
* [`isNaN()`](../isnan)
javascript Number.parseInt() Number.parseInt()
=================
The `Number.parseInt()` static method parses a string argument and returns an integer of the specified radix or base.
Try it
------
Syntax
------
```
Number.parseInt(string)
Number.parseInt(string, radix)
```
### Parameters
`string` The value to parse, [coerced to a string](../string#string_coercion). Leading 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`.
If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed.
### Return value
An integer parsed from the given `string`.
If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../nan) is returned.
Examples
--------
### Number.parseInt vs parseInt
This method has the same functionality as the global [`parseInt()`](../parseint) function:
```
Number.parseInt === parseInt // true
```
Its purpose is modularization of globals. Please see [`parseInt()`](../parseint) for more detail and examples.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.parseint](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.parseint) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 34 | 12 | 25 | No | 21 | 9 | 37 | 34 | 25 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Number.parseInt` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* The [`Number`](../number) object it belongs to.
* The global [`parseInt()`](../parseint) method.
javascript Number.isSafeInteger() Number.isSafeInteger()
======================
The `Number.isSafeInteger()` static method determines whether the provided value is a number that is a *safe integer*.
Try it
------
Syntax
------
```
Number.isSafeInteger(testValue)
```
### Parameters
`testValue` The value to be tested for being a safe integer.
### Return value
The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`.
Description
-----------
The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (Β±9,007,199,254,740,991). A safe integer is an integer that:
* can be exactly represented as an IEEE-754 double precision number, and
* whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.
For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is *not* a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding.
Handling values larger or smaller than ~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers.
For larger integers, consider using the [`BigInt`](../bigint) type.
Examples
--------
### Using isSafeInteger()
```
Number.isSafeInteger(3); // true
Number.isSafeInteger(2 \*\* 53); // false
Number.isSafeInteger(2 \*\* 53 - 1); // true
Number.isSafeInteger(NaN); // false
Number.isSafeInteger(Infinity); // false
Number.isSafeInteger("3"); // false
Number.isSafeInteger(3.1); // false
Number.isSafeInteger(3.0); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.issafeinteger](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.issafeinteger) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isSafeInteger` | 34 | 12 | 32 | No | 21 | 9 | 37 | 34 | 32 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Number.isSafeInteger` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* The [`Number`](../number) object it belongs to.
* [`Number.MIN_SAFE_INTEGER`](min_safe_integer)
* [`Number.MAX_SAFE_INTEGER`](max_safe_integer)
* [`BigInt`](../bigint)
javascript Number.MIN_VALUE Number.MIN\_VALUE
=================
The `Number.MIN_VALUE` property represents the smallest positive numeric value representable in JavaScript.
Try it
------
Value
-----
2-1074, or `5E-324`.
| Property attributes of `Number.MIN_VALUE` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision β in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support β instead the spec says, *"must be the smallest non-zero positive value that can actually be represented by the implementation"*. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger.
In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`.
Because `MIN_VALUE` is a static property of [`Number`](../number), you always use it as `Number.MIN_VALUE`, rather than as a property of a number value.
Examples
--------
### Using MIN\_VALUE
The following code divides two numeric values. If the result is greater than or equal to `MIN_VALUE`, the `func1` function is called; otherwise, the `func2` function is called.
```
if (num1 / num2 >= Number.MIN\_VALUE) {
func1();
} else {
func2();
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.min\_value](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.min_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 |
| `MIN_VALUE` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.MAX_VALUE`](max_value)
javascript Number.isInteger() Number.isInteger()
==================
The `Number.isInteger()` static method determines whether the passed value is an integer.
Try it
------
Syntax
------
```
Number.isInteger(value)
```
### Parameters
`value` The value to be tested for being an integer.
### Return value
The boolean value `true` if the given value is an integer. Otherwise `false`.
Description
-----------
If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../nan) or [`Infinity`](../infinity), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number.
Note that some number literals, while looking like non-integers, actually represent integers β due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](epsilon) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`.
In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](max_safe_integer) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal β for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.)
Examples
--------
### Using isInteger
```
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(99999999999999999999999); // true
Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger(NaN); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger("10"); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false
Number.isInteger(5.0); // true
Number.isInteger(5.000000000000001); // false
Number.isInteger(5.0000000000000001); // true, because of loss of precision
Number.isInteger(4500000000000000.1); // true, because of loss of precision
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.isinteger](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.isinteger) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isInteger` | 34 | 12 | 16 | No | 21 | 9 | 37 | 34 | 16 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Number.isInteger` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* The [`Number`](../number) object it belongs to.
| programming_docs |
javascript Number.EPSILON Number.EPSILON
==============
The `Number.EPSILON` property represents the difference between 1 and the smallest floating point number greater than 1.
Try it
------
Value
-----
2-52, or approximately `2.2204460492503130808472633361816E-16`.
| Property attributes of `Number.EPSILON` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](../number#number_encoding), and the lowest bit has a significance of 2-52.
Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. [`Number.MIN_VALUE`](min_value) is the smallest representable positive number, which is much smaller than `Number.EPSILON`.
Because `EPSILON` is a static property of [`Number`](../number), you always use it as `Number.EPSILON`, rather than as a property of a number value.
Examples
--------
### Testing equality
Any number encoding system occupying a finite number of bits, of whatever base you choose (e.g. decimal or binary), will *necessarily* be unable to represent all numbers exactly, because you are trying to represent an infinite number of points on the number line using a finite amount of memory. For example, a base-10 (decimal) system cannot represent 1/3 exactly, and a base-2 (binary) system cannot represent `0.1` exactly. Thus, for example, `0.1 + 0.2` is not exactly equal to `0.3`:
```
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
```
For this reason, it is often advised that `===`. Instead, we can deem two numbers as equal if they are *close enough* to each other. The `Number.EPSILON` constant is usually a reasonable threshold for errors if the arithmetic is around the magnitude of `1`, because `EPSILON`, in essence, specifies how accurate the number "1" is.
```
function equal(x, y) {
return Math.abs(x - y) < Number.EPSILON;
}
const x = 0.2;
const y = 0.3;
const z = 0.1;
console.log(equal(x + z, y)); // true
```
However, `Number.EPSILON` is inappropriate for any arithmetic operating on a larger magnitude. If your data is on the 103 order of magnitude, the decimal part will have a much smaller accuracy than `Number.EPSILON`:
```
function equal(x, y) {
return Math.abs(x - y) < Number.EPSILON;
}
const x = 1000.1;
const y = 1000.2;
const z = 2000.3;
console.log(x + y); // 2000.3000000000002; error of 10^-13 instead of 10^-16
console.log(equal(x + y, z)); // false
```
In this case, a larger tolerance is required. As the numbers compared have a magnitude of approximately `2000`, a multiplier such as `2000 * Number.EPSILON` creates enough tolerance for this instance.
```
function equal(x, y, tolerance = Number.EPSILON) {
return Math.abs(x - y) < tolerance;
}
const x = 1000.1;
const y = 1000.2;
const z = 2000.3;
console.log(equal(x + y, z, 2000 \* Number.EPSILON)); // true
```
In addition to magnitude, it is important to consider the *accuracy* of your input. For example, if the numbers are collected from a form input and the input value can only be adjusted by steps of `0.1` (i.e. [`<input type="number" step="0.1">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/step)), it usually makes sense to allow a much larger tolerance, such as `0.01`, since the data only has a precision of `0.1`.
**Note:** Important takeaway: do not simply use `Number.EPSILON` as a threshold for equality testing. Use a threshold that is appropriate for the magnitude and accuracy of the numbers you are comparing.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.epsilon](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.epsilon) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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 |
See also
--------
* [Polyfill of `Number.EPSILON` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* The [`Number`](../number) object it belongs to
javascript Number.prototype.toPrecision() Number.prototype.toPrecision()
==============================
The `toPrecision()` method returns a string representing the [`Number`](../number) object to the specified precision.
Try it
------
Syntax
------
```
toPrecision()
toPrecision(precision)
```
### Parameters
`precision` Optional
An integer specifying the number of significant digits.
### Return value
A string representing a [`Number`](../number) object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](tofixed) method, which also applies to `toPrecision()`.
If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](tostring). If the `precision` argument is a non-integer value, it is rounded to the nearest integer.
### Exceptions
[`RangeError`](../rangeerror) If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../rangeerror) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits.
Examples
--------
### Using `toPrecision`
```
let num = 5.123456;
console.log(num.toPrecision()); // '5.123456'
console.log(num.toPrecision(5)); // '5.1235'
console.log(num.toPrecision(2)); // '5.1'
console.log(num.toPrecision(1)); // '5'
num = 0.000123;
console.log(num.toPrecision()); // '0.000123'
console.log(num.toPrecision(5)); // '0.00012300'
console.log(num.toPrecision(2)); // '0.00012'
console.log(num.toPrecision(1)); // '0.0001'
// note that exponential notation might be returned in some circumstances
console.log((1234.5).toPrecision(2)); // '1.2e+3'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.prototype.toprecision](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.toprecision) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toPrecision` | 1 | 12 | 1 | 5.5 | 7 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.prototype.toFixed()`](tofixed)
* [`Number.prototype.toExponential()`](toexponential)
* [`Number.prototype.toString()`](tostring)
javascript Number.NaN Number.NaN
==========
The `Number.NaN` property represents Not-A-Number, which is equivalent to [`NaN`](../nan). For more information about the behaviors of `NaN`, see the [description for the global property](../nan).
Try it
------
Value
-----
The number value [`NaN`](../nan).
| Property attributes of `Number.NaN` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
Because `NaN` is a static property of [`Number`](../number), you always use it as `Number.NaN`, rather than as a property of a number value.
Examples
--------
### Checking whether values are numeric
```
function sanitize(x) {
if (isNaN(x)) {
return Number.NaN;
}
return x;
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.nan](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.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 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`NaN`](../nan)
* [`Number.isNaN()`](isnan)
javascript Number.prototype.toString() Number.prototype.toString()
===========================
The `toString()` method returns a string representing the specified number value.
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 number value. Defaults to 10.
### Return value
A string representing the specified number value.
### Exceptions
[`RangeError`](../rangeerror) Thrown if `radix` is less than 2 or greater than 36.
Description
-----------
The [`Number`](../number) object overrides the `toString` method of [`Object`](../object); it does not inherit [`Object.prototype.toString()`](../object/tostring). For `Number` values, the `toString` method returns a string representation of the value in the specified radix.
For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used.
If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value.
Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../infinity) returns `"Infinity"` and [`NaN`](../nan) returns `"NaN"`.
If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](../../lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent.
```
console.log((10 \*\* 21.5).toString()); // "3.1622776601683794e+21"
console.log((10 \*\* 21.5).toString(8)); // "526665530627250154000000"
```
The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../typeerror) for other `this` values without attempting to coerce them to number values.
Because `Number` doesn't have a [`[@@toPrimitive]()`](../symbol/toprimitive) method, JavaScript calls the `toString()` method automatically when a `Number` *object* is used in a context expecting a string, such as in a [template literal](../../template_literals). However, Number *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.
```
Number.prototype.toString = () => "Overridden";
console.log(`${1}`); // "1"
console.log(`${new Number(1)}`); // "Overridden"
```
Examples
--------
### Using toString()
```
const count = 10;
console.log(count.toString()); // "10"
console.log((17).toString()); // "17"
console.log((17.2).toString()); // "17.2"
const x = 6;
console.log(x.toString(2)); // "110"
console.log((254).toString(16)); // "fe"
console.log((-10).toString(2)); // "-1010"
console.log((-0xff).toString(2)); // "-11111111"
```
### Converting radix of number strings
If you have a string representing a number in a non-decimal radix, you can use [`parseInt()`](../parseint) and `toString()` to convert it to a different radix.
```
const hex = "CAFEBABE";
const bin = parseInt(hex, 16).toString(2); // "11001010111111101011101010111110"
```
Beware of loss of precision: if the original number string is too large (larger than [`Number.MAX_SAFE_INTEGER`](max_safe_integer), for example), you should use a [`BigInt`](../bigint/bigint) instead. However, the `BigInt` constructor only has support for strings representing number literals (i.e. strings starting with `0b`, `0o`, `0x`). In case your original radix is not one of binary, octal, decimal, or hexadecimal, you may need to hand-write your radix converter, or use a library.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number.prototype.tostring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.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 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.prototype.toFixed()`](tofixed)
* [`Number.prototype.toExponential()`](toexponential)
* [`Number.prototype.toPrecision()`](toprecision)
javascript Generator.prototype.throw() Generator.prototype.throw()
===========================
The `throw()` method of a 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
------
```
generatorObject.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 exception is caught by a [`try...catch`](../../statements/try...catch) and the generator resumes to yield more values, it will return 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.
### Exceptions
If the thrown exception is not caught by a `try...catch`, the `exception` passed to `throw()` will be thrown out from the generator function.
Description
-----------
The `throw()` method, when called, can be seen as if a `throw exception;` statement is inserted in the generator's body at the current suspended position, where `exception` is the exception passed to the `throw()` method. Therefore, in a typical flow, calling `throw(exception)` will cause the generator to throw. However, if the `yield` expression is wrapped in a `try...catch` block, the error may be caught and control flow can either resume after error handling, or exit gracefully.
Examples
--------
### 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.
```
function\* gen() {
while (true) {
try {
yield 42;
} catch (e) {
console.log('Error caught!');
}
}
}
const g = gen();
g.next();
// { value: 42, done: false }
g.throw(new Error('Something went wrong'));
// "Error caught!"
// { value: 42, done: false }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generator.prototype.throw](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-generator.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` | 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*)
javascript Generator.prototype.next() Generator.prototype.next()
==========================
The `next()` method returns an object with two properties `done` and `value`. You can also provide a parameter to the `next` method to send a value to the generator.
Syntax
------
```
generatorObject.next(value)
```
### Parameters
`value` The value to send to the generator.
The value will be assigned as a result of a `yield` expression. For example, in `variable = yield expression`, the value passed to the `.next()` function will be assigned to `variable`.
### Return value
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:
```
function\* gen() {
yield 1;
yield 2;
yield 3;
}
const g = gen(); // "Generator { }"
g.next(); // "Object { value: 1, done: false }"
g.next(); // "Object { value: 2, done: false }"
g.next(); // "Object { value: 3, done: false }"
g.next(); // "Object { value: undefined, done: true }"
```
### Using next() with a list
In this example, `getPage` takes a list and "paginates" it into chunks of size `pageSize`. Each call to `next` will yield one such chunk.
```
function\* getPage(list, pageSize = 1) {
for (let index = 0; index < list.length; index += pageSize) {
yield list.slice(index, index + pageSize);
}
}
const list = [1, 2, 3, 4, 5, 6, 7, 8]
const page = getPage(list, 3); // Generator { }
page.next(); // { value: [1, 2, 3], done: false }
page.next(); // { value: [4, 5, 6], done: false }
page.next(); // { value: [7, 8], done: false }
page.next(); // { 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.
```
function\* gen() {
while (true) {
const value = yield;
console.log(value);
}
}
const g = gen();
g.next(1); // Returns { value: undefined, done: false }
// No log at this step: the first value sent through `next` is lost
g.next(2); // Returns { value: undefined, done: false }
// Logs 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generator.prototype.next](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-generator.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` | 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*)
* [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
javascript Generator.prototype.return() Generator.prototype.return()
============================
The `return()` method of a 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
------
```
generatorObject.return(value)
```
### Parameters
`value` The value to return.
### Return value
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 generator and the `return` method.
```
function\* gen() {
yield 1;
yield 2;
yield 3;
}
const g = gen();
g.next(); // { value: 1, done: false }
g.return('foo'); // { value: "foo", done: true }
g.next(); // { value: undefined, done: true }
```
If `return(value)` is called on a generator that is already in "completed" state, the generator will remain in "completed" state.
If no argument is provided, the `value` property of the returned object will be `undefined`. If an argument is provided, it will become the value of the `value` property of the returned object, unless the `yield` expression is wrapped in a `try...finally`.
```
function\* gen() {
yield 1;
yield 2;
yield 3;
}
const g = gen();
g.next(); // { value: 1, done: false }
g.next(); // { value: 2, done: false }
g.next(); // { value: 3, done: false }
g.next(); // { value: undefined, done: true }
g.return(); // { value: undefined, done: true }
g.return(1); // { value: 1, done: true }
```
### Using return() with try...finally
The fact that the `return` method has been called can only be made known to the generator itself if the `yield` expression is wrapped in a `try...finally` block.
When the `return` method is called on a generator that is suspended within a `try` block, execution in the generator proceeds to the `finally` block β since the `finally` block of `try...finally` statements always executes.
```
function\* gen() {
yield 1;
try {
yield 2;
yield 3;
} finally {
yield 'cleanup';
}
}
const g1 = gen();
g1.next(); // { value: 1, done: false }
// Execution is suspended before the try...finally.
g1.return('early return'); // { value: 'early return', done: true }
const g2 = gen();
g2.next(); // { value: 1, done: false }
g2.next(); // { value: 2, done: false }
// Execution is suspended within the try...finally.
g2.return('early return'); // { value: 'cleanup', done: false }
// The completion value is preserved
g2.next(); // { value: 'early return', done: true }
// Generator is in the completed state
g2.return('not so early return'); // { value: 'not so early return', done: true }
```
The return value of the finally block can also become the `value` of the result returned from the `return` call.
```
function\* gen() {
try {
yield 1;
} finally {
return 'cleanup';
}
}
const g1 = gen();
g1.next(); // { value: 1, done: false }
g1.return('early return'); // { value: 'cleanup', done: true }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generator.prototype.return](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-generator.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` | 50 | 13 | 38 | No | 37 | 10 | 50 | 50 | 38 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`function*`](../../statements/function*)
| programming_docs |
javascript ReferenceError() constructor ReferenceError() constructor
============================
The `ReferenceError` object represents an error when a non-existent variable is referenced.
Syntax
------
```
new ReferenceError()
new ReferenceError(message)
new ReferenceError(message, options)
new ReferenceError(message, fileName)
new ReferenceError(message, fileName, lineNumber)
ReferenceError()
ReferenceError(message)
ReferenceError(message, options)
ReferenceError(message, fileName)
ReferenceError(message, fileName, lineNumber)
```
**Note:** `ReferenceError()` can be called with or without [`new`](../../operators/new). Both create a new `ReferenceError` 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 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-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 |
| `ReferenceError` | 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)
javascript Map.prototype.size Map.prototype.size
==================
The `size` accessor property returns the number of elements in a [`Map`](../map) object.
Try it
------
Description
-----------
The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property.
Examples
--------
### Using size
```
const myMap = new Map();
myMap.set('a', 'alpha');
myMap.set('b', 'beta');
myMap.set('g', 'gamma');
console.log(myMap.size); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-map.prototype.size](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-get-map.prototype.size) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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 |
See also
--------
* [`Map`](../map)
javascript Map() constructor Map() constructor
=================
The `Map()` creates [`Map`](../map) objects.
Syntax
------
```
new Map()
new Map(iterable)
```
**Note:** `Map()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`iterable` Optional
An [`Array`](../array) or other [iterable](../../iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`.
Examples
--------
### Creating a new Map
```
const myMap = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map-constructor](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map-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 |
| `Map` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `iterable_allowed` | 38 | 12 | 13 | No | 25 | 9 | 38 | 38 | 14 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `new_required` | 38 | 12 | 42 | 11 | 25 | 9 | 38 | 38 | 42 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `null_allowed` | 38 | 12 | 37 | 11 | 25 | 9 | 38 | 38 | 37 | 25 | 9 | 3.0 | 1.0 | 0.12.0
0.10.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)
javascript Map.prototype.has() Map.prototype.has()
===================
The `has()` method returns a boolean indicating whether an element with the specified key exists or not.
Try it
------
Syntax
------
```
has(key)
```
### Parameters
`key` The key of the element to test for presence in the `Map` object.
### Return value
`true` if an element with the specified key exists in the `Map` object; otherwise `false`.
Examples
--------
### Using has()
```
const myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.has("bar")); // true
console.log(myMap.has("baz")); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.has](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`Map`](../map)
* [`Map.prototype.set()`](set)
* [`Map.prototype.get()`](get)
javascript Map.prototype.values() Map.prototype.values()
======================
The `values()` method returns a new *[iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)* object that contains the values for each element in the `Map` object in insertion order.
Try it
------
Syntax
------
```
values()
```
### Return value
A new [`Map`](../map) iterator object.
Examples
--------
### Using values()
```
const myMap = new Map();
myMap.set('0', 'foo');
myMap.set(1, 'bar');
myMap.set({}, 'baz');
const mapIter = myMap.values();
console.log(mapIter.next().value); // "foo"
console.log(mapIter.next().value); // "bar"
console.log(mapIter.next().value); // "baz"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.values](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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 | 20 | No | 25 | 8 | 38 | 38 | 20 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Map.prototype.entries()`](entries)
* [`Map.prototype.keys()`](keys)
javascript Map.prototype.keys() Map.prototype.keys()
====================
The `keys()` method returns a new *[iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)* object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](../../statements/for...of) loop can be used.
Try it
------
Syntax
------
```
keys()
```
### Return value
A new [`Map`](../map) iterator object.
Examples
--------
### Using keys()
```
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap.keys();
console.log(mapIter.next().value); // "0"
console.log(mapIter.next().value); // 1
console.log(mapIter.next().value); // {}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.keys](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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 | 20 | No | 25 | 8 | 38 | 38 | 20 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Map.prototype.entries()`](entries)
* [`Map.prototype.values()`](values)
javascript Map.prototype[@@iterator]() Map.prototype[@@iterator]()
===========================
The `@@iterator` method of a `Map` object implements the [iterable protocol](../../iteration_protocols) and allows maps 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 key-value pairs of the map.
The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](entries) property.
Try it
------
Syntax
------
```
map[Symbol.iterator]()
```
### Return value
The same return value as [`Map.prototype.entries()`](entries): a new iterable iterator object that yields the key-value pairs of the map.
Examples
--------
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `Map` 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 myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const entry of myMap) {
console.log(entry);
}
// ["0", "foo"]
// [1, "bar"]
// [{}, "baz"]
for (const [key, value] of myMap) {
console.log(`${key}: ${value}`);
}
// 0: foo
// 1: bar
// [Object]: baz
```
### 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 myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap[Symbol.iterator]();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype-@@iterator](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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
--------
* [`Map.prototype.entries()`](entries)
* [`Map.prototype.keys()`](keys)
* [`Map.prototype.values()`](values)
javascript Map.prototype.clear() Map.prototype.clear()
=====================
The `clear()` method removes all elements from a `Map` object.
Try it
------
Syntax
------
```
clear()
```
### Return value
[`undefined`](../undefined).
Examples
--------
### Using clear()
```
const myMap = new Map();
myMap.set('bar', 'baz');
myMap.set(1, 'foo');
console.log(myMap.size); // 2
console.log(myMap.has('bar')); // true
myMap.clear();
console.log(myMap.size); // 0
console.log(myMap.has('bar')); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.clear](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.clear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `clear` | 38 | 12 | 19 | 11 | 25 | 8 | 38 | 38 | 19 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Map`](../map)
javascript Map.prototype.entries() Map.prototype.entries()
=======================
The `entries()` method returns a new *[iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)* object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself.
Try it
------
Syntax
------
```
entries()
```
### Return value
A new [`Map`](../map) iterator object.
Examples
--------
### Using entries()
```
const myMap = new Map();
myMap.set('0', 'foo');
myMap.set(1, 'bar');
myMap.set({}, 'baz');
const mapIter = myMap.entries();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.entries](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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 | 20 | No | 25 | 8 | 38 | 38 | 20 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Map.prototype.keys()`](keys)
* [`Map.prototype.values()`](values)
javascript get Map[@@species] get Map[@@species]
==================
The `Map[@@species]` accessor property is an unused accessor property specifying how to copy `Map` objects.
Syntax
------
```
Map[Symbol.species]
```
### Return value
The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `Map` instances.
Description
-----------
The `@@species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment.
**Note:** This property is currently unused by all `Map` methods.
Examples
--------
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is the `Map` constructor for `Map`.
```
Map[Symbol.species]; // function Map()
```
### Species in derived objects
In an instance of a custom `Map` subclass, such as `MyMap`, the `MyMap` species is the `MyMap` constructor. However, you might want to overwrite this, in order to return parent `Map` objects in your derived class methods:
```
class MyMap extends Map {
// Overwrite MyMap species to the parent Map constructor
static get [Symbol.species]() {
return Map;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-map-@@species](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-get-map-@@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 | 41 | No | 38 | 10 | 51 | 51 | 41 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* [`Map`](../map)
* [`Symbol.species`](../symbol/species)
javascript Map.prototype.set() Map.prototype.set()
===================
The `set()` method adds or updates an entry in a `Map` object with a specified key and a value.
Try it
------
Syntax
------
```
set(key, value)
```
### Parameters
`key` The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects)).
`value` The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects)).
### Return value
The `Map` object.
Examples
--------
### Using set()
```
const myMap = new Map();
// Add new elements to the map
myMap.set('bar', 'foo');
myMap.set(1, 'foobar');
// Update an element in the map
myMap.set('bar', 'baz');
```
### Using the set() with chaining
Since the `set()` method returns back the same `Map` object, you can chain the method call like below:
```
// Add new elements to the map with chaining.
myMap.set('bar', 'foo')
.set(1, 'foobar')
.set(2, 'baz');
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.set](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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` | 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 |
See also
--------
* [`Map`](../map)
* [`Map.prototype.get()`](get)
* [`Map.prototype.has()`](has)
| programming_docs |
javascript Map.prototype.delete() Map.prototype.delete()
======================
The `delete()` method removes the specified element from a `Map` object by key.
Try it
------
Syntax
------
```
delete(key)
```
### Parameters
`key` The key of the element to remove from the `Map` object.
### Return value
`true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist.
Examples
--------
### Using delete()
```
const myMap = new Map();
myMap.set('bar', 'foo');
console.log(myMap.delete('bar')); // Returns true. Successfully removed.
console.log(myMap.has('bar')); // Returns false. The "bar" element is no longer present.
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.delete](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`Map`](../map)
javascript Map.prototype.get() Map.prototype.get()
===================
The `get()` method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object.
Try it
------
Syntax
------
```
get(key)
```
### Parameters
`key` The key of the element to return from the `Map` object.
### Return value
The element associated with the specified key, or [`undefined`](../undefined) if the key can't be found in the `Map` object.
Examples
--------
### Using get()
```
const myMap = new Map();
myMap.set('bar', 'foo');
console.log(myMap.get('bar')); // Returns "foo"
console.log(myMap.get('baz')); // Returns undefined
```
### Using get() to retrieve a reference to an object
```
const arr = [];
const myMap = new Map();
myMap.set('bar', arr);
myMap.get('bar').push('foo');
console.log(arr); // ["foo"]
console.log(myMap.get('bar')); // ["foo"]
```
Note that the map holding a reference to the original object effectively means the object cannot be garbage-collected, which may lead to unexpected memory issues. If you want the object stored in the map to have the same lifespan as the original one, consider using a [`WeakMap`](../weakmap).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.get](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`Map`](../map)
* [`Map.prototype.set()`](set)
* [`Map.prototype.has()`](has)
javascript Map.prototype.forEach() Map.prototype.forEach()
=======================
The `forEach()` method executes a provided function once per each key/value pair in the `Map` object, in insertion order.
Try it
------
Syntax
------
```
// Arrow function
forEach(() => { /\* β¦ \*/ } )
forEach((value) => { /\* β¦ \*/ } )
forEach((value, key) => { /\* β¦ \*/ } )
forEach((value, key, map) => { /\* β¦ \*/ } )
// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)
// Inline callback function
forEach(function() { /\* β¦ \*/ })
forEach(function(value) { /\* β¦ \*/ })
forEach(function(value, key) { /\* β¦ \*/ })
forEach(function(value, key, map) { /\* β¦ \*/ })
forEach(function(value, key, map) { /\* β¦ \*/ }, thisArg)
```
### Parameters
`callbackFn` Function to execute for each entry in the map. It takes the following arguments:
`value` Optional
Value of each iteration.
`key` Optional
Key of each iteration.
`map` Optional
The map being iterated.
`thisArg` Optional
Value to use as `this` when executing `callback`.
### Return value
[`undefined`](../undefined).
Description
-----------
The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`.
`callback` is invoked with **three arguments**:
* the entry's `value`
* the entry's `key`
* the `Map` being traversed
If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](../../operators/this).
Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited.
Examples
--------
### Printing the contents of a Map object
The following code logs a line for each element in an `Map` object:
```
function logMapElements(value, key, map) {
console.log(`map.get('${key}') = ${value}`);
}
new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements);
// Logs:
// "map.get('foo') = 3"
// "map.get('bar') = [object Object]"
// "map.get('baz') = undefined"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map.prototype.foreach](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.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` | 38 | 12 | 25 | 11 | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Array.prototype.forEach()`](../array/foreach)
* [`Set.prototype.forEach()`](../set/foreach)
javascript BigUint64Array() constructor BigUint64Array() constructor
============================
The `BigUint64Array()` typed array constructor creates a new [`BigUint64Array`](../biguint64array) object, which is, 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).
Syntax
------
```
new BigUint64Array()
new BigUint64Array(length)
new BigUint64Array(typedArray)
new BigUint64Array(object)
new BigUint64Array(buffer)
new BigUint64Array(buffer, byteOffset)
new BigUint64Array(buffer, byteOffset, length)
```
**Note:** `BigUint64Array()` 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 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-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 |
| `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 JSON.stringify() JSON.stringify()
================
The `JSON.stringify()` static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Try it
------
Syntax
------
```
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
```
### Parameters
`value` The value to convert to a JSON string.
`replacer` Optional
A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of `value` to be included in the output. If `replacer` is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including [`Symbol`](../symbol) values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](../../operators/null) or not provided), all string-keyed properties of the object are included in the resulting JSON string.
`space` Optional
A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes.
If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used.
If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array.
If `space` is anything other than a string or number (can be either a primitive or a wrapper object) β for example, is [`null`](../../operators/null) or not provided β no white space is used.
### Return value
A JSON string representing the given value, or undefined.
### Exceptions
[`TypeError`](../typeerror) Thrown if one of the following is true:
* `value` contains a circular reference.
* A [`BigInt`](../bigint) value is encountered.
Description
-----------
`JSON.stringify()` converts a value to JSON notation representing it:
* [`Boolean`](../boolean), [`Number`](../number), [`String`](../string), and [`BigInt`](../bigint) (obtainable via [`Object()`](../object/object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. [`Symbol`](../symbol) objects (obtainable via [`Object()`](../object/object)) are treated as plain objects.
* Attempting to serialize [`BigInt`](../bigint) values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user.
* [`undefined`](../undefined), [`Function`](../function), and [`Symbol`](../symbol) values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](../../operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`.
* The numbers [`Infinity`](../infinity) and [`NaN`](../nan), as well as the value [`null`](../../operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.)
* Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored.
* For other objects:
+ All [`Symbol`](../symbol)-keyed properties will be completely ignored, even when using the [`replacer`](#the_replacer_parameter) parameter.
+ If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the_replacer_parameter) function:
- if this object is a property value, the property name
- if it is in an array, the index in the array, as a string
- if `JSON.stringify()` was directly called on this object, an empty string[`Date`](../date) objects implement the [`toJSON()`](../date/tojson) method which returns a string (the same as [`date.toISOString()`](../date/toisostring)). Thus, they will be stringified as strings.
+ Only [enumerable own properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [`Map`](../map), [`Set`](../set), etc. will become `"{}"`. You can use the [`replacer`](#the_replacer_parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](../object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable).
### The replacer parameter
The `replacer` parameter can be either a function or an array.
As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored.
As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context.
The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means:
* If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.)
* If you return a [`Function`](../function), [`Symbol`](../symbol), or [`undefined`](../undefined), the property is not included in the output.
* If you return any other object, the object is recursively stringified, calling the `replacer` function on each property.
**Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](parse#using_the_reviver_parameter) parameter to perform the reverse operation.
Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array.
### The space parameter
The `space` parameter may be used to control spacing in the final string.
* If it is a number, successive levels in the stringification will each be indented by this many space characters.
* If it is a string, successive levels will be indented by this string.
Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters.
Examples
--------
### Using JSON.stringify
```
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify("foo"); // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'
JSON.stringify({ x: 5 }); // '{"x":5}'
JSON.stringify(new Date(1906, 0, 2, 15, 4, 5));
// '"1906-01-02T15:04:05.000Z"'
JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}'
JSON.stringify([new Number(3), new String("false"), new Boolean(false)]);
// '[3,"false",false]'
// String-keyed array elements are not enumerable and make no sense in JSON
const a = ["foo", "bar"];
a["baz"] = "quux"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]
JSON.stringify(a);
// '["foo","bar"]'
JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] });
// '{"x":[10,null,null,null]}'
// Standard data structures
JSON.stringify([
new Set([1]),
new Map([[1, 2]]),
new WeakSet([{ a: 1 }]),
new WeakMap([[{ a: 1 }, 2]]),
]);
// '[{},{},{},{}]'
// TypedArray
JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]);
// '[{"0":1},{"0":1},{"0":1}]'
JSON.stringify([
new Uint8Array([1]),
new Uint8ClampedArray([1]),
new Uint16Array([1]),
new Uint32Array([1]),
]);
// '[{"0":1},{"0":1},{"0":1},{"0":1}]'
JSON.stringify([new Float32Array([1]), new Float64Array([1])]);
// '[{"0":1},{"0":1}]'
// toJSON()
JSON.stringify({
x: 5,
y: 6,
toJSON() {
return this.x + this.y;
},
});
// '11'
// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol("") });
// '{}'
JSON.stringify({ [Symbol("foo")]: "foo" });
// '{}'
JSON.stringify({ [Symbol.for("foo")]: "foo" }, [Symbol.for("foo")]);
// '{}'
JSON.stringify({ [Symbol.for("foo")]: "foo" }, (k, v) => {
if (typeof k === "symbol") {
return "a symbol";
}
});
// undefined
// Non-enumerable properties:
JSON.stringify(
Object.create(null, {
x: { value: "x", enumerable: false },
y: { value: "y", enumerable: true },
}),
);
// '{"y":"y"}'
// BigInt values throw
JSON.stringify({ x: 2n });
// TypeError: BigInt value can't be serialized in JSON
```
### Using a function as replacer
```
function replacer(key, value) {
// Filtering out properties
if (typeof value === "string") {
return undefined;
}
return value;
}
const foo = {
foundation: "Mozilla",
model: "box",
week: 45,
transport: "car",
month: 7,
};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
```
If you wish the `replacer` to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key).
```
function makeReplacer() {
let isInitial = true;
return (key, value) => {
if (isInitial) {
isInitial = false;
return value;
}
if (key === "") {
// Omit all properties with name "" (except the initial object)
return undefined;
}
return value;
};
}
const replacer = makeReplacer();
console.log(JSON.stringify({ "": 1, b: 2 }, replacer)); // "{"b":2}"
```
### Using an array as replacer
```
const foo = {
foundation: "Mozilla",
model: "box",
week: 45,
transport: "car",
month: 7,
};
JSON.stringify(foo, ["week", "month"]);
// '{"week":45,"month":7}', only keep "week" and "month" properties
```
### Using the space parameter
Indent the output with one space:
```
console.log(JSON.stringify({ a: 2 }, null, " "));
/\*
{
"a": 2
}
\*/
```
Using a tab character mimics standard pretty-print appearance:
```
console.log(JSON.stringify({ uno: 1, dos: 2 }, null, "\t"));
/\*
{
"uno": 1,
"dos": 2
}
\*/
```
### toJSON() behavior
Defining `toJSON()` for an object allows overriding its serialization behavior.
```
const obj = {
data: "data",
toJSON(key) {
return key ? `Now I am a nested object under key '${key}'` : this;
},
};
JSON.stringify(obj);
// '{"data":"data"}'
JSON.stringify({ obj });
// '{"obj":"Now I am a nested object under key 'obj'"}'
JSON.stringify([obj]);
// '["Now I am a nested object under key '0'"]'
```
### Issue with serializing circular references
Since the [JSON format](https://www.json.org/) doesn't support object references (although an [IETF draft exists](https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03)), a [`TypeError`](../typeerror) will be thrown if one attempts to encode an object with circular references.
```
const circularReference = {};
circularReference.myself = circularReference;
// Serializing circular references throws "TypeError: cyclic object value"
JSON.stringify(circularReference);
```
To serialize circular references, you can use a library that supports them (e.g. [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/cycle.js) by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.
If you are using `JSON.stringify()` to deep-copy an object, you may instead want to use [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone), which supports circular references. JavaScript engine APIs for binary serialization, such as [`v8.serialize()`](https://nodejs.org/api/v8.html#v8serializevalue), also support circular references.
### Using JSON.stringify() with localStorage
In a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of `JSON.stringify()`:
```
// Creating an example of JSON
const session = {
screens: [],
state: true,
};
session.screens.push({ name: "screenA", width: 450, height: 250 });
session.screens.push({ name: "screenB", width: 650, height: 350 });
session.screens.push({ name: "screenC", width: 750, height: 120 });
session.screens.push({ name: "screenD", width: 250, height: 60 });
session.screens.push({ name: "screenE", width: 390, height: 120 });
session.screens.push({ name: "screenF", width: 1240, height: 650 });
// Converting the JSON string with JSON.stringify()
// then saving with localStorage in the name of session
localStorage.setItem("session", JSON.stringify(session));
// Example of how to transform the String generated through
// JSON.stringify() and saved in localStorage in JSON object again
const restoredSession = JSON.parse(localStorage.getItem("session"));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
```
### Well-formed JSON.stringify()
Engines implementing the [well-formed JSON.stringify specification](https://github.com/tc39/proposal-well-formed-stringify) will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16:
```
JSON.stringify("\uD800"); // '"οΏ½"'
```
But with this change `JSON.stringify()` represents lone surrogates using JSON escape sequences that *can* be encoded in valid UTF-8 or UTF-16:
```
JSON.stringify("\uD800"); // '"\\ud800"'
```
This change should be backwards-compatible as long as you pass the result of `JSON.stringify()` to APIs such as `JSON.parse()` that will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. *Only* if you are directly interpreting the result of `JSON.stringify()` do you need to carefully handle `JSON.stringify()`'s two possible encodings of these code points.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-json.stringify](https://tc39.es/ecma262/multipage/structured-data.html#sec-json.stringify) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `stringify` | 3 | 12 | 3.5 | 8 | 10.5 | 4 | β€37 | 18 | 4 | 11 | 4 | 1.0 | 1.0 | 0.10.0 |
| `well_formed_stringify` | 72 | 79 | 64 | No | 60 | 12.1 | 72 | 72 | 64 | 50 | 12.2 | 11.0 | 1.0 | 12.0.0 |
See also
--------
* [Polyfill of modern `JSON.stringify` behavior (symbol and well-formed unicode) in `core-js`](https://github.com/zloirock/core-js#ecmascript-json)
* [`JSON.parse()`](parse)
| programming_docs |
javascript JSON.parse() JSON.parse()
============
The `JSON.parse()` static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional *reviver* function can be provided to perform a transformation on the resulting object before it is returned.
Try it
------
Syntax
------
```
JSON.parse(text)
JSON.parse(text, reviver)
```
### Parameters
`text` The string to parse as JSON. See the [`JSON`](../json) object for a description of JSON syntax.
`reviver` Optional
If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:
`key` The key associated with the value.
`value` The value produced by parsing.
### Return value
The [`Object`](../object), [`Array`](../array), string, number, boolean, or `null` value corresponding to the given JSON `text`.
### Exceptions
[`SyntaxError`](../syntaxerror) Thrown if the string to parse is not valid JSON.
Description
-----------
`JSON.parse()` parses a JSON string according to the [JSON grammar](../json#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key β see [Object literal syntax vs. JSON](../../operators/object_initializer#object_literal_syntax_vs._json).
### The reviver parameter
If a `reviver` is specified, the value computed by parsing is *transformed* before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`.
The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../undefined) (or returns no value β for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is β otherwise, they will be deleted from the resulting object.
Similar to the `replacer` parameter of [`JSON.stringify()`](stringify), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once.
Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](../bigint), or other appropriate arbitrary precision formats.
Examples
--------
### Using JSON.parse()
```
JSON.parse("{}"); // {}
JSON.parse("true"); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse("null"); // null
```
### Using the reviver parameter
```
JSON.parse(
'{"p": 5}',
(key, value) =>
typeof value === "number"
? value \* 2 // return value \* 2 for numbers
: value, // return everything else unchanged
);
// { p: 10 }
JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
console.log(key);
return value;
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""
```
### Using reviver when paired with the replacer of JSON.stringify()
In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the `replacer` parameter of [`JSON.stringify()`](stringify) for this purpose:
```
// Maps are normally serialized as objects with no properties.
// We can use the replacer to specify the entries to be serialized.
const map = new Map([
[1, "one"],
[2, "two"],
[3, "three"],
]);
const jsonText = JSON.stringify(
map,
(key, value) => (value instanceof Map ? Array.from(value.entries()) : value),
);
console.log(jsonText);
// [[1,"one"],[2,"two"],[3,"three"]]
const map2 = JSON.parse(
jsonText,
(key, value) => (key === "" ? new Map(value) : value),
);
console.log(map2);
// Map { 1 => "one", 2 => "two", 3 => "three" }
```
Because JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:
* Serialize the entire object to a string and prefix it with a type tag.
* "Guess" based on the structure of the data (for example, an array of two-member arrays)
* If the shape of the payload is fixed, based on the property name (for example, all properties called `registry` hold `Map` objects).
### JSON.parse() does not allow trailing commas
```
// both will throw a SyntaxError
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');
```
### JSON.parse() does not allow single quotes
```
// will throw a SyntaxError
JSON.parse("{'foo': 1}");
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-json.parse](https://tc39.es/ecma262/multipage/structured-data.html#sec-json.parse) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `parse` | 3 | 12 | 3.5 | 8 | 10.5 | 4 | β€37 | 18 | 4 | 11 | 4 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`JSON.stringify()`](stringify)
javascript AggregateError() constructor AggregateError() constructor
============================
The `AggregateError()` constructor creates an error for several errors that need to be wrapped in a single error.
Syntax
------
```
new AggregateError(errors)
new AggregateError(errors, message)
new AggregateError(errors, message, options)
AggregateError(errors)
AggregateError(errors, message)
AggregateError(errors, message, options)
```
**Note:** `AggregateError()` can be called with or without [`new`](../../operators/new). Both create a new `AggregateError` instance.
### Parameters
`errors` An iterable of errors, may not actually be [`Error`](../error) instances.
`message` Optional
An optional human-readable description of the aggregate 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.
Examples
--------
### 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-constructor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-aggregate-error-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 |
| `AggregateError` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
See also
--------
* [Polyfill of `AggregateError` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise)
* [`Promise.any`](../promise/any)
javascript SharedArrayBuffer.prototype.byteLength SharedArrayBuffer.prototype.byteLength
======================================
The `byteLength` accessor property represents the length of an [`SharedArrayBuffer`](../sharedarraybuffer) in bytes.
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 the shared array is constructed and cannot be changed.
Examples
--------
### Using byteLength
```
const sab = new SharedArrayBuffer(1024);
sab.byteLength; // 1024
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-sharedarraybuffer.prototype.bytelength](https://tc39.es/ecma262/multipage/structured-data.html#sec-get-sharedarraybuffer.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` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`SharedArrayBuffer`](../sharedarraybuffer)
javascript SharedArrayBuffer() constructor SharedArrayBuffer() constructor
===============================
**Note:** `SharedArrayBuffer` was disabled by default in all major browsers on 5 January, 2018 in response to [Spectre](https://meltdownattack.com/). Chrome [re-enabled it in v67](https://bugs.chromium.org/p/chromium/issues/detail?id=821270) on platforms where its site-isolation feature is enabled to protect against Spectre-style vulnerabilities.
The `SharedArrayBuffer()` is used to create a [`SharedArrayBuffer`](../sharedarraybuffer) object representing a generic, fixed-length raw binary data buffer, similar to the [`ArrayBuffer`](../arraybuffer) object.
Try it
------
Syntax
------
```
new SharedArrayBuffer()
new SharedArrayBuffer(length)
```
**Note:** `SharedArrayBuffer()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`length` Optional
The size, in bytes, of the array buffer to create.
### Return value
A new `SharedArrayBuffer` object of the specified size. Its contents are initialized to 0.
Examples
--------
### Always use the new operator to create a SharedArrayBuffer
`SharedArrayBuffer` constructors are required to be constructed with a [`new`](../../operators/new) operator. Calling a `SharedArrayBuffer` constructor as a function without `new` will throw a [`TypeError`](../typeerror).
```
const sab = SharedArrayBuffer(1024);
// TypeError: calling a builtin SharedArrayBuffer constructor
// without new is forbidden
```
```
const sab = new SharedArrayBuffer(1024);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-sharedarraybuffer-constructor](https://tc39.es/ecma262/multipage/structured-data.html#sec-sharedarraybuffer-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 |
| `SharedArrayBuffer` | 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)
javascript SharedArrayBuffer.prototype.slice() SharedArrayBuffer.prototype.slice()
===================================
The `SharedArrayBuffer.prototype.slice()` method returns a new [`SharedArrayBuffer`](../sharedarraybuffer) whose contents are a copy of this `SharedArrayBuffer`'s bytes from begin, inclusive, up to end, exclusive. If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. This method has the same algorithm as [`Array.prototype.slice()`](../array/slice).
Try it
------
Syntax
------
```
slice()
slice(begin)
slice(begin, end)
```
### Parameters
`begin` 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 `begin` 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 (`sab.byteLength`).
### Return value
A new [`SharedArrayBuffer`](../sharedarraybuffer) containing the extracted elements.
Examples
--------
### Using slice()
```
const sab = new SharedArrayBuffer(1024);
sab.slice(); // SharedArrayBuffer { byteLength: 1024 }
sab.slice(2); // SharedArrayBuffer { byteLength: 1022 }
sab.slice(-2); // SharedArrayBuffer { byteLength: 2 }
sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-sharedarraybuffer.prototype.slice](https://tc39.es/ecma262/multipage/structured-data.html#sec-sharedarraybuffer.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` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`SharedArrayBuffer`](../sharedarraybuffer)
* [`Array.prototype.slice()`](../array/slice)
javascript Object.freeze() Object.freeze()
===============
The `Object.freeze()` static method *freezes* an object. Freezing an object [prevents extensions](preventextensions) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in.
Freezing an object is the highest integrity level that JavaScript provides.
Try it
------
Syntax
------
```
Object.freeze(obj)
```
### Parameters
`obj` The object to freeze.
### Return value
The object that was passed to the function.
Description
-----------
Freezing an object is equivalent to [preventing extensions](preventextensions) and then changing all existing [properties' descriptors'](defineproperty#description) `configurable` to `false` β and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../typeerror) exception (most commonly, but not exclusively, when in [strict mode](../../strict_mode)).
For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same β the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array.
`freeze()` returns the same object that was passed into the function. It *does not* create a frozen copy.
A [`TypedArray`](../typedarray) or a [`DataView`](../dataview) with elements will cause a [`TypeError`](../typeerror), as they are views over memory and will definitely cause other possible issues:
```
Object.freeze(new Uint8Array(0)) // No elements
// Uint8Array []
Object.freeze(new Uint8Array(1)) // Has elements
// TypeError: Cannot freeze array buffer views with elements
Object.freeze(new DataView(new ArrayBuffer(32))) // No elements
// DataView {}
Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements
// Float64Array []
Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements
// TypeError: Cannot freeze array buffer views with elements
```
Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an [`ArrayBuffer`](../arraybuffer) or [`SharedArrayBuffer`](../sharedarraybuffer)), there is no reason for attempting to freeze these properties.
Unlike [`Object.seal()`](seal), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned.
Examples
--------
### Freezing objects
```
const obj = {
prop() {},
foo: 'bar'
};
// Before freezing: new properties may be added,
// and existing properties may be changed or removed
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;
// Freeze.
const o = Object.freeze(obj);
// The return value is just the same object we passed in.
o === obj; // true
// The object has become frozen.
Object.isFrozen(obj); // === true
// Now any changes will fail
obj.foo = 'quux'; // silently does nothing
// silently doesn't add the property
obj.quaxxor = 'the friendly duck';
// In strict mode such attempts will throw TypeErrors
function fail() {
'use strict';
obj.foo = 'sparky'; // throws a TypeError
delete obj.foo; // throws a TypeError
delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added
obj.sparky = 'arf'; // throws a TypeError
}
fail();
// Attempted changes through Object.defineProperty;
// both statements below throw a TypeError.
Object.defineProperty(obj, 'ohai', { value: 17 });
Object.defineProperty(obj, 'foo', { value: 'eit' });
// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 })
obj.__proto__ = { x: 20 }
```
### Freezing arrays
```
const a = [0];
Object.freeze(a); // The array cannot be modified now.
a[0] = 1; // fails silently
// In strict mode such attempt will throw a TypeError
function fail() {
"use strict";
a[0] = 1;
}
fail();
// Attempted to push
a.push(2); // throws a TypeError
```
The object being frozen is *immutable*. However, it is not necessarily *constant*. The following example shows that a frozen object is not constant (freeze is shallow).
```
const obj1 = {
internal: {}
};
Object.freeze(obj1);
obj1.internal.a = 'aValue';
obj1.internal.a // 'aValue'
```
To be a constant object, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects. The object being frozen is said to be immutable because the entire object *state* (values and references to other objects) within the whole object is fixed. Note that strings, numbers, and booleans are always immutable and that Functions and Arrays are objects.
#### What is "shallow freeze"?
The result of calling `Object.freeze(object)` only applies to the immediate properties of `object` itself and will prevent future property addition, removal or value re-assignment operations *only* on `object`. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.
```
const employee = {
name: "Mayank",
designation: "Developer",
address: {
street: "Rohini",
city: "Delhi"
}
};
Object.freeze(employee);
employee.name = "Dummy"; // fails silently in non-strict mode
employee.address.city = "Noida"; // attributes of child object can be modified
console.log(employee.address.city); // "Noida"
```
To make an object immutable, recursively freeze each non-primitive property (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no [cycles](https://en.wikipedia.org/wiki/Cycle_(graph_theory)) in the reference graph, otherwise an endless loop will be triggered. An enhancement to `deepFreeze()` would be to have an internal function that receives a path (e.g. an Array) argument so you can suppress calling `deepFreeze()` recursively when an object is in the process of being made immutable. You still run a risk of freezing an object that shouldn't be frozen, such as [window].
```
function deepFreeze(object) {
// Retrieve the property names defined on object
const propNames = Reflect.ownKeys(object);
// Freeze properties before freezing self
for (const name of propNames) {
const value = object[name];
if ((value && typeof value === "object") || typeof value === "function") {
deepFreeze(value);
}
}
return Object.freeze(object);
}
const obj2 = {
internal: {
a: null
}
};
deepFreeze(obj2);
obj2.internal.a = 'anotherValue'; // fails silently in non-strict mode
obj2.internal.a; // null
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.freeze](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.freeze) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `freeze` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.isFrozen()`](isfrozen)
* [`Object.preventExtensions()`](preventextensions)
* [`Object.isExtensible()`](isextensible)
* [`Object.seal()`](seal)
* [`Object.isSealed()`](issealed)
| programming_docs |
javascript Object.prototype.__lookupGetter__() Object.prototype.\_\_lookupGetter\_\_()
=======================================
**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:** This feature is deprecated in favor of the [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The `__lookupGetter__()` method returns the function bound as a getter to the specified property.
Syntax
------
```
\_\_lookupGetter\_\_(prop)
```
### Parameters
`prop` A string containing the name of the property whose getter should be returned.
### Return value
The function bound as a getter to the specified property. Returns `undefined` if no such property is found, or the property is a [data property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#data_property).
Description
-----------
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `__lookupGetter__()` method. If a [getter](../../functions/get) has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. `__lookupGetter__()` can be used to obtain a reference to the getter function.
`__lookupGetter__()` walks up the [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) to find the specified property. If any object along the prototype chain has the specified [own property](hasown), the `get` attribute of the [property descriptor](getownpropertydescriptor) for that property is returned. If that property is a data property, `undefined` is returned. If the property is not found along the entire prototype chain, `undefined` is also returned.
`__lookupGetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__lookupGetter__()`, it also needs to implement the [`__lookupSetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__), [`__defineGetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__), and [`__defineSetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__) methods.
Examples
--------
### Using \_\_lookupGetter\_\_()
```
const obj = {
get foo() {
return Math.random() > 0.5 ? "foo" : "bar";
},
};
obj.\_\_lookupGetter\_\_("foo");
// [Function: get foo]
```
### Looking up a property's getter in the standard way
You should use the [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) API to look up a property's getter. Compared to `__lookupGetter__()`, this method allows looking up [symbol](../symbol) properties. The `Object.getOwnPropertyDescriptor()` method also works with [`null`-prototype objects](../object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__lookupGetter__()` method. If `__lookupGetter__()`'s behavior of walking up the prototype chain is important, you may implement it yourself with [`Object.getPrototypeOf()`](getprototypeof).
```
const obj = {
get foo() {
return Math.random() > 0.5 ? "foo" : "bar";
},
};
Object.getOwnPropertyDescriptor(obj, "foo").get;
// [Function: get foo]
```
```
const obj2 = {
\_\_proto\_\_: {
get foo() {
return Math.random() > 0.5 ? "foo" : "bar";
},
},
};
function findGetter(obj, prop) {
while (obj) {
const desc = Object.getOwnPropertyDescriptor(obj, "foo");
if (desc) {
return desc.get;
}
obj = Object.getPrototypeOf(obj);
}
}
console.log(findGetter(obj2, "foo")); // [Function: get foo]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.\_\_lookupGetter\_\_](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-object.prototype.__lookupGetter__) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `__lookupGetter__` | 1 | 12 | 1 | 11 | 9.5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.prototype.__lookupGetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.prototype.__lookupSetter__()`](__lookupsetter__)
* [`get`](../../functions/get) syntax
* [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) and [`Object.getPrototypeOf()`](getprototypeof)
* [`Object.prototype.__defineGetter__()`](__definegetter__)
* [`Object.prototype.__defineSetter__()`](__definesetter__)
* [JS Guide: Defining Getters and Setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#defining_getters_and_setters)
javascript Object.prototype.toLocaleString() Object.prototype.toLocaleString()
=================================
The `toLocaleString()` method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes.
Try it
------
Syntax
------
```
toLocaleString()
```
### Parameters
None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString`](../date/tolocalestring). The parameter positions should not be used for any other purpose.
### Return value
The return value of calling `this.toString()`.
Description
-----------
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `toLocaleString()` method. [`Object`](../object)'s `toLocaleString` returns the result of calling [`this.toString()`](tostring).
This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting:
* [`Array`](../array): [`Array.prototype.toLocaleString()`](../array/tolocalestring)
* [`Number`](../number): [`Number.prototype.toLocaleString()`](../number/tolocalestring)
* [`Date`](../date): [`Date.prototype.toLocaleString()`](../date/tolocalestring)
* [`TypedArray`](../typedarray): [`TypedArray.prototype.toLocaleString()`](../typedarray/tolocalestring)
* [`BigInt`](../bigint): [`BigInt.prototype.toLocaleString()`](../bigint/tolocalestring)
Examples
--------
### Using the base toLocaleString() method
The base `toLocaleString()` method simply calls `toString()`.
```
const obj = {
toString() {
return "My Object";
}
};
console.log(obj.toLocaleString()); // "My Object"
```
### Array toLocaleString() override
[`Array.prototype.toLocaleString()`](../array/tolocalestring) is used to print array values as a string by invoking each element's `toLocaleString()` method and joining the results with a locale-specific separator. For example:
```
const testArray = [4, 7, 10];
const euroPrices = testArray.toLocaleString("fr", {
style: "currency",
currency: "EUR",
});
// "4,00 β¬,7,00 β¬,10,00 β¬"
```
### Date toLocaleString() override
[`Date.prototype.toLocaleString()`](../date/tolocalestring) is used to print out date displays more suitable for specific locales. For example:
```
const testDate = new Date();
// "Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)"
const deDate = testDate.toLocaleString("de");
// "29.5.2020, 18:04:24"
const frDate = testDate.toLocaleString("fr");
// "29/05/2020, 18:04:24"
```
### Number toLocaleString() override
[`Number.prototype.toLocaleString()`](../number/tolocalestring) is used to print out number displays more suitable for specific locales, e.g. with the correct separators. For example:
```
const testNumber = 2901234564;
// "2901234564"
const deNumber = testNumber.toLocaleString("de");
// "2.901.234.564"
const frNumber = testNumber.toLocaleString("fr");
// "2 901 234 564"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.tolocalestring](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.prototype.toString()`](tostring)
javascript Object.values() Object.values()
===============
The `Object.values()` static method returns an array of a given object's own enumerable string-keyed property values.
Try it
------
Syntax
------
```
Object.values(obj)
```
### Parameters
`obj` An object.
### Return value
An array containing the given object's own enumerable string-keyed property values.
Description
-----------
`Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a [`for...in`](../../statements/for...in) loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a [`for...in`](../../statements/for...in) loop.
If you need the property keys, use [`Object.keys()`](keys) instead. If you need both the property keys and values, use [`Object.entries()`](entries) instead.
Examples
--------
### Using Object.values()
```
const obj = { foo: "bar", baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
// Array-like object
const arrayLikeObj1 = { 0: "a", 1: "b", 2: "c" };
console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c']
// Array-like object with random key ordering
// When using numeric keys, the values are returned in the keys' numerical order
const arrayLikeObj2 = { 100: "a", 2: "b", 7: "c" };
console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a']
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = "bar";
console.log(Object.values(myObj)); // ['bar']
```
### Using Object.values() on primitives
Non-object arguments are [coerced to objects](../object#object_coercion). Only strings may have own enumerable properties, while all other primitives return an empty array.
```
// Strings have indices as enumerable own properties
console.log(Object.values("foo")); // ['f', 'o', 'o']
// Other primitives have no own properties
console.log(Object.values(100)); // []
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.values](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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` | 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
--------
* [Polyfill of `Object.values` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.keys()`](keys)
* [`Object.entries()`](entries)
* [`Object.prototype.propertyIsEnumerable()`](propertyisenumerable)
* [`Object.create()`](create)
* [`Object.getOwnPropertyNames()`](getownpropertynames)
* [`Map.prototype.values()`](../map/values)
javascript Object.prototype.propertyIsEnumerable() Object.prototype.propertyIsEnumerable()
=======================================
The `propertyIsEnumerable()` method 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.
Try it
------
Syntax
------
```
propertyIsEnumerable(prop)
```
### Parameters
`prop` The name of the property to test. Can be a string or a [`Symbol`](../symbol).
### Return value
A boolean value indicating whether the specified property is enumerable and is the object's own property.
Description
-----------
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`.
This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](getownpropertydescriptor).
Examples
--------
### Using propertyIsEnumerable()
The following example shows the use of `propertyIsEnumerable()` on objects and arrays.
```
const o = {};
const a = [];
o.prop = "is enumerable";
a[0] = "is enumerable";
o.propertyIsEnumerable("prop"); // true
a.propertyIsEnumerable(0); // true
```
### User-defined vs. built-in objects
Most built-in properties are non-enumerable by default, while user-created object properties are often enumerable, unless explicitly designated otherwise.
```
const a = ["is enumerable"];
a.propertyIsEnumerable(0); // true
a.propertyIsEnumerable("length"); // false
Math.propertyIsEnumerable("random"); // false
globalThis.propertyIsEnumerable("Math"); // false
```
### Direct vs. inherited properties
Only enumerable own properties cause `propertyIsEnumerable()` to return `true`, although all enumerable properties, including inherited ones, are visited by the [`for...in`](../../statements/for...in) loop.
```
const o1 = {
enumerableInherited: "is enumerable",
};
Object.defineProperty(o1, "nonEnumerableInherited", {
value: "is non-enumerable",
enumerable: false,
});
const o2 = {
// o1 is the prototype of o2
\_\_proto\_\_: o1,
enumerableOwn: "is enumerable",
};
Object.defineProperty(o2, "nonEnumerableOwn", {
value: "is non-enumerable",
enumerable: false,
});
o2.propertyIsEnumerable("enumerableInherited"); // false
o2.propertyIsEnumerable("nonEnumerableInherited"); // false
o2.propertyIsEnumerable("enumerableOwn"); // true
o2.propertyIsEnumerable("nonEnumerableOwn"); // false
```
### Testing symbol properties
[`Symbol`](../symbol) properties are also supported by `propertyIsEnumerable()`. Note that most enumeration methods only visit string properties; enumerability of symbol properties is only useful when using [`Object.assign()`](assign) or [spread syntax](../../operators/spread_syntax). For more information, see [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties).
```
const sym = Symbol("enumerable");
const sym2 = Symbol("non-enumerable");
const o = {
[sym]: "is enumerable",
};
Object.defineProperty(o, sym2, {
value: "is non-enumerable",
enumerable: false,
});
o.propertyIsEnumerable(sym); // true
o.propertyIsEnumerable(sym2); // false
```
### Usage with null-prototype objects
Because `null`-prototype objects do not inherit from `Object.prototype`, they do not inherit the `propertyIsEnumerable()` method. You must call `Object.prototype.propertyIsEnumerable` with the object as `this` instead.
```
const o = {
\_\_proto\_\_: null,
enumerableOwn: "is enumerable",
};
o.propertyIsEnumerable("enumerableOwn"); // TypeError: o.propertyIsEnumerable is not a function
Object.prototype.propertyIsEnumerable.call(o, "enumerableOwn"); // true
```
Alternatively, you may use [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) instead, which also helps to distinguish between non-existent properties and actually non-enumerable properties.
```
const o = {
\_\_proto\_\_: null,
enumerableOwn: "is enumerable",
};
Object.getOwnPropertyDescriptor(o, "enumerableOwn")?.enumerable; // true
Object.getOwnPropertyDescriptor(o, "nonExistent")?.enumerable; // undefined
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.propertyisenumerable](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.prototype.propertyisenumerable) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `propertyIsEnumerable` | 1 | 12 | 1 | 5.5 | 4 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`for...in`](../../statements/for...in)
* [`Object.keys()`](keys)
* [`Object.defineProperty()`](defineproperty)
javascript Object.fromEntries() Object.fromEntries()
====================
The `Object.fromEntries()` static method transforms a list of key-value pairs into an object.
Try it
------
Syntax
------
```
Object.fromEntries(iterable)
```
### Parameters
`iterable` An [iterable](../../iteration_protocols#the_iterable_protocol), such as an [`Array`](../array) or [`Map`](../map), containing a list of objects. Each object should have two properties:
`0` A string or [symbol](../symbol) representing the property key.
`1` The property value.
Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value.
### Return value
A new object whose properties are given by the entries of the iterable.
Description
-----------
The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key.
`Object.fromEntries()` performs the reverse of [`Object.entries()`](entries), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties.
**Note:** Unlike [`Array.from()`](../array/from), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type.
Examples
--------
### Converting a Map to an Object
With `Object.fromEntries`, you can convert from [`Map`](../map) to [`Object`](../object):
```
const map = new Map([
["foo", "bar"],
["baz", 42],
]);
const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }
```
### Converting an Array to an Object
With `Object.fromEntries`, you can convert from [`Array`](../array) to [`Object`](../object):
```
const arr = [
["0", "a"],
["1", "b"],
["2", "c"],
];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
```
### Object transformations
With `Object.fromEntries`, its reverse method [`Object.entries()`](entries), and [array manipulation methods](../array#instance_methods), you are able to transform objects like this:
```
const object1 = { a: 1, b: 2, c: 3 };
const object2 = Object.fromEntries(
Object.entries(object1).map(([key, val]) => [key, val \* 2]),
);
console.log(object2);
// { a: 2, b: 4, c: 6 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.fromentries](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.fromentries) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fromEntries` | 73 | 79 | 63 | No | 60 | 12.1 | 73 | 73 | 63 | 52 | 12.2 | 11.0 | 1.0 | 12.0.0 |
See also
--------
* [Polyfill of `Object.fromEntries` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.entries()`](entries)
* [`Object.keys()`](keys)
* [`Object.values()`](values)
* [`Object.prototype.propertyIsEnumerable()`](propertyisenumerable)
* [`Object.create()`](create)
* [`Map.prototype.entries()`](../map/entries)
* [`Map.prototype.keys()`](../map/keys)
* [`Map.prototype.values()`](../map/values)
| programming_docs |
javascript Object.hasOwn() Object.hasOwn()
===============
The `Object.hasOwn()` static method returns `true` if the specified object has the indicated property as its *own* property. If the property is inherited, or does not exist, the method returns `false`.
**Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](hasownproperty).
Try it
------
Syntax
------
```
Object.hasOwn(obj, prop)
```
### Parameters
`obj` The JavaScript object instance to test.
`prop` The [`String`](../string) name or [Symbol](../symbol) of the property to test.
### Return value
`true` if the specified object has directly defined the specified property. Otherwise `false`
Description
-----------
The `Object.hasOwn()` method returns `true` if the specified property is a direct property of the object β even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the [`in`](../../operators/in) operator, this method does not check for the specified property in the object's prototype chain.
It is recommended over [`Object.prototype.hasOwnProperty()`](hasownproperty) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive.
Examples
--------
### Using hasOwn to test for a property's existence
The following code shows how to determine whether the `example` object contains a property named `prop`.
```
const example = {};
Object.hasOwn(example, 'prop'); // false - 'prop' has not been defined
example.prop = 'exists';
Object.hasOwn(example, 'prop'); // true - 'prop' has been defined
example.prop = null;
Object.hasOwn(example, 'prop'); // true - own property exists with value of null
example.prop = undefined;
Object.hasOwn(example, 'prop'); // true - own property exists with value of undefined
```
### Direct vs. inherited properties
The following example differentiates between direct properties and properties inherited through the prototype chain:
```
const example = {};
example.prop = 'exists';
// `hasOwn` will only return true for direct properties:
Object.hasOwn(example, 'prop'); // returns true
Object.hasOwn(example, 'toString'); // returns false
Object.hasOwn(example, 'hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in example; // returns true
'toString' in example; // returns true
'hasOwnProperty' in example; // returns true
```
### Iterating over the properties of an object
To iterate over the enumerable properties of an object, you *should* use:
```
const example = { foo: true, bar: true };
for (const name of Object.keys(example)) {
// β¦
}
```
But if you need to use `for...in`, you can use `Object.hasOwn()` to skip the inherited properties:
```
const example = { foo: true, bar: true };
for (const name in example) {
if (Object.hasOwn(example, name)) {
// β¦
}
}
```
### Checking if an Array index exists
The elements of an [`Array`](../array) are defined as direct properties, so you can use `hasOwn()` method to check whether a particular index exists:
```
const fruits = ['Apple', 'Banana','Watermelon', 'Orange'];
Object.hasOwn(fruits, 3); // true ('Orange')
Object.hasOwn(fruits, 4); // false - not defined
```
### Problematic cases for hasOwnProperty
This section demonstrates that `hasOwn()` is immune to the problems that affect `hasOwnProperty`. Firstly, it can be used with objects that have reimplemented `hasOwnProperty()`:
```
const foo = {
hasOwnProperty() {
return false;
},
bar: 'The dragons be out of office',
};
if (Object.hasOwn(foo, 'bar')) {
console.log(foo.bar); //true - reimplementation of hasOwnProperty() does not affect Object
}
```
It can also be used to test objects created using [`Object.create(null)`](create). These do not inherit from `Object.prototype`, and so `hasOwnProperty()` is inaccessible.
```
const foo = Object.create(null);
foo.prop = 'exists';
if (Object.hasOwn(foo, 'prop')) {
console.log(foo.prop); //true - works irrespective of how the object is created.
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.hasown](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.hasown) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `hasOwn` | 93 | 93 | 92 | No | 79 | 15.4 | 93 | 93 | 92 | 66 | 15.4 | 17.0 | 1.13 | 16.9.0 |
See also
--------
* [Polyfill of `Object.hasOwn` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.prototype.hasOwnProperty()`](hasownproperty)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.getOwnPropertyNames()`](getownpropertynames)
* [`for...in`](../../statements/for...in)
* [`in`](../../operators/in)
* [JavaScript Guide: Inheritance revisited](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
javascript Object.prototype.constructor Object.prototype.constructor
============================
The `constructor` data property of an [`Object`](../object) instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to *the function itself*, not a string containing the function's name.
**Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](../../classes/constructor).
Value
-----
A reference to the constructor function that created the instance object.
| Property attributes of `Object.prototype.constructor` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
**Note:** This property is created by default on the [`prototype`](../function/prototype) property of every constructor function and is inherited by all objects created by that constructor.
Description
-----------
Any object (with the exception of [`null` prototype objects](../object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object β for example, array literals create [`Array`](../array) objects, and [object literals](../../operators/object_initializer) create plain objects.
```
const o1 = {};
o1.constructor === Object; // true
const o2 = new Object();
o2.constructor === Object; // true
const a1 = [];
a1.constructor === Array; // true
const a2 = new Array();
a2.constructor === Array; // true
const n = 3;
n.constructor === Number; // true
```
Note that `constructor` usually comes from the constructor's [`prototype`](../function/prototype) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property.
```
const o = new TypeError(); // Inheritance: TypeError -> Error -> Object
const proto = Object.getPrototypeOf;
proto(o).constructor === TypeError; // true
proto(proto(o)).constructor === Error; // true
proto(proto(proto(o))).constructor === Object; // true
```
Examples
--------
### Displaying the constructor of an object
The following example creates a constructor (`Tree`) and an object of that type (`theTree`). The example then displays the `constructor` property for the object `theTree`.
```
function Tree(name) {
this.name = name;
}
const theTree = new Tree("Redwood");
console.log(`theTree.constructor is ${theTree.constructor}`);
```
This example displays the following output:
```
theTree.constructor is function Tree(name) {
this.name = name;
}
```
### Assigning the constructor property to an object
One can assign the `constructor` property of non-primitives.
```
const arr = [];
arr.constructor = String;
arr.constructor === String; // true
arr instanceof String; // false
arr instanceof Array; // true
const foo = new Foo();
foo.constructor = "bar";
foo.constructor === "bar"; // true
// etc.
```
This does not overwrite the old `constructor` property β it was originally present on the instance's `[[Prototype]]`, not as its own property.
```
const arr = [];
Object.hasOwn(arr, "constructor"); // false
Object.hasOwn(Object.getPrototypeOf(arr), "constructor"); // true
arr.constructor = String;
Object.hasOwn(arr, "constructor"); // true β the instance property shadows the one on its prototype
```
But even when `Object.getPrototypeOf(a).constructor` is re-assigned, it won't change other behaviors of the object. For example, the behavior of `instanceof` is controlled by [`Symbol.hasInstance`](../symbol/hasinstance), not `constructor`:
```
const arr = [];
arr.constructor = String;
arr instanceof String; // false
arr instanceof Array; // true
```
There is nothing protecting the `constructor` property from being re-assigned or shadowed, so using it to detect the type of a variable should usually be avoided in favor of less fragile ways like `instanceof` and [`Symbol.toStringTag`](../symbol/tostringtag) for objects, or [`typeof`](../../operators/typeof) for primitives.
### Changing the constructor of a constructor function's prototype
Every constructor has a [`prototype`](../function/prototype) property, which will become the instance's `[[Prototype]]` when called via the [`new`](../../operators/new) operator. `ConstructorFunction.prototype.constructor` will therefore become a property on the instance's `[[Prototype]]`, as previously demonstrated.
However, if `ConstructorFunction.prototype` is re-assigned, the `constructor` property will be lost. For example, the following is a common way to create an inheritance pattern:
```
function Parent() {
// β¦
}
Parent.prototype.parentMethod = function () {};
function Child() {
Parent.call(this); // Make sure everything is initialized properly
}
// Pointing the [[Prototype]] of Child.prototype to Parent.prototype
Child.prototype = Object.create(Parent.prototype);
```
The `constructor` of instances of `Child` will be `Parent` due to `Child.prototype` being re-assigned.
This is usually not a big deal β the language almost never reads the `constructor` property of an object. The only exception is when using [`@@species`](../symbol/species) to create new instances of a class, but such cases are rare, and you should be using the [`extends`](../../classes/extends) syntax to subclass builtins anyway.
However, ensuring that `Child.prototype.constructor` always points to `Child` itself is crucial when some caller is using `constructor` to access the original class from an instance. Take the following case: the object has the `create()` method to create itself.
```
function Parent() {
// β¦
}
function CreatedConstructor() {
Parent.call(this);
}
CreatedConstructor.prototype = Object.create(Parent.prototype);
CreatedConstructor.prototype.create = function () {
return new this.constructor();
};
new CreatedConstructor().create().create(); // TypeError: new CreatedConstructor().create().create is undefined, since constructor === Parent
```
In the example above, an exception is thrown, since the `constructor` links to `Parent`. To avoid this, just assign the necessary constructor you are going to use.
```
function Parent() {
// β¦
}
function CreatedConstructor() {
// β¦
}
CreatedConstructor.prototype = Object.create(Parent.prototype, {
// Return original constructor to Child
constructor: {
value: CreatedConstructor,
enumerable: false, // Make it non-enumerable, so it won't appear in `for...in` loop
writable: true,
configurable: true,
},
});
CreatedConstructor.prototype.create = function () {
return new this.constructor();
};
new CreatedConstructor().create().create(); // it's pretty fine
```
Note that when manually adding the `constructor` property, it's crucial to make the property [non-enumerable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties), so `constructor` won't be visited in [`for...in`](../../statements/for...in) loops β as it normally isn't.
If the code above looks like too much boilerplate, you may also consider using [`Object.setPrototypeOf()`](setprototypeof) to manipulate the prototype chain.
```
function Parent() {
// β¦
}
function CreatedConstructor() {
// β¦
}
Object.setPrototypeOf(CreatedConstructor.prototype, Parent.prototype);
CreatedConstructor.prototype.create = function () {
return new this.constructor();
};
new CreatedConstructor().create().create(); // still works without re-creating constructor property
```
`Object.setPrototypeOf()` comes with its potential performance downsides because all previously created objects involved in the prototype chain have to be re-compiled; but if the above initialization code happens before `Parent` or `CreatedConstructor` are constructed, the effect should be minimal.
Let's consider one more involved case.
```
function ParentWithStatic() {}
ParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property
ParentWithStatic.getStartPosition = function () {
return this.startPosition;
};
function Child(x, y) {
this.position = { x, y };
}
Child.prototype = Object.create(ParentWithStatic.prototype, {
// Return original constructor to Child
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true,
},
});
Child.prototype.getOffsetByInitialPosition = function () {
const position = this.position;
// Using this.constructor, in hope that getStartPosition exists as a static method
const startPosition = this.constructor.getStartPosition();
return {
offsetX: startPosition.x - position.x,
offsetY: startPosition.y - position.y,
};
};
new Child(1, 1).getOffsetByInitialPosition();
// Error: this.constructor.getStartPosition is undefined, since the
// constructor is Child, which doesn't have the getStartPosition static method
```
For this example to work properly, we can reassign the `Parent`'s static properties to `Child`:
```
// β¦
Object.assign(Child, ParentWithStatic); // Notice that we assign it before we create() a prototype below
Child.prototype = Object.create(ParentWithStatic.prototype, {
// Return original constructor to Child
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true,
},
});
// β¦
```
But even better, we can make the constructor functions themselves extend each other, as classes' [`extends`](../../classes/extends) do.
```
function ParentWithStatic() {}
ParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property
ParentWithStatic.getStartPosition = function () {
return this.startPosition;
};
function Child(x, y) {
this.position = { x, y };
}
// Properly create inheritance!
Object.setPrototypeOf(Child.prototype, ParentWithStatic.prototype);
Object.setPrototypeOf(Child, ParentWithStatic);
Child.prototype.getOffsetByInitialPosition = function () {
const position = this.position;
const startPosition = this.constructor.getStartPosition();
return {
offsetX: startPosition.x - position.x,
offsetY: startPosition.y - position.y,
};
};
console.log(new Child(1, 1).getOffsetByInitialPosition()); // { offsetX: -1, offsetY: -1 }
```
Again, using `Object.setPrototypeOf()` may have adverse performance effects, so make sure it happens immediately after the constructor declaration and before any instances are created β to avoid objects being "tainted".
**Note:** Manually updating or setting the constructor can lead to different and sometimes confusing consequences. To prevent this, just define the role of `constructor` in each specific case. In most cases, `constructor` is not used and reassigning it is not necessary.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.constructor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.prototype.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 |
| `constructor` | 1 | 12 | 1 | 8 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Class declaration`](../../statements/class)
* [`Class constructor`](../../classes/constructor)
* Glossary: [constructor](https://developer.mozilla.org/en-US/docs/Glossary/Constructor)
javascript Object.prototype.valueOf() Object.prototype.valueOf()
==========================
The `valueOf()` method of [`Object`](../object) converts the `this` value [to an object](../object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion) logic.
Try it
------
Syntax
------
```
valueOf()
```
### Parameters
None.
### Return value
The `this` value, converted to an object.
**Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`.
Description
-----------
JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
This method is called in priority by [numeric conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](../string#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](tostring) base implementation), so `valueOf()` is usually not called in this case.
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object β unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`@@toPrimitive`](../symbol/toprimitive) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion.
Examples
--------
### Using valueOf()
The base `valueOf()` method returns the `this` value itself, converted to an object if it isn't already. Therefore its return value will never be used by any primitive conversion algorithm.
```
const obj = { foo: 1 };
console.log(obj.valueOf() === obj); // true
console.log(Object.prototype.valueOf.call("primitive"));
// [String: 'primitive'] (a wrapper object)
```
### Overriding valueOf for custom objects
You can create a function to be called in place of the default `valueOf` method. Your function should take no arguments, since it won't be passed any when called during type conversion.
For example, you can add a `valueOf` method to your custom class `Box`.
```
class Box {
#value;
constructor(value) {
this.#value = value;
}
valueOf() {
return this.#value;
}
}
```
With the preceding code in place, any time an object of type `Box` is used in a context where it is to be represented as a primitive value (but not specifically a string), JavaScript automatically calls the function defined in the preceding code.
```
const box = new Box(123);
console.log(box + 456); // 579
console.log(box == 123); // true
```
An object's `valueOf` method is usually invoked by JavaScript, but you can invoke it yourself as follows:
```
box.valueOf();
```
### Using unary plus on objects
[Unary plus](../../operators/unary_plus) performs [number coercion](../number#number_coercion) on its operand, which, for most objects without [`@@toPrimitive`](../symbol/toprimitive), means calling its `valueOf()`. However, if the object doesn't have a custom `valueOf()` method, the base implementation will cause `valueOf()` to be ignored and the return value of `toString()` to be used instead.
```
+new Date(); // the current timestamp; same as new Date().getTime()
+{}; // NaN (toString() returns "[object Object]")
+[]; // 0 (toString() returns an empty string list)
+[1]; // 1 (toString() returns "1")
+[1, 2]; // NaN (toString() returns "1,2")
+new Set([1]); // NaN (toString() returns "[object Set]")
+{ valueOf: () => 42 }; // 42
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.valueof](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.prototype.toString()`](tostring)
* [`parseInt()`](../parseint)
* [`Symbol.toPrimitive`](../symbol/toprimitive)
| programming_docs |
javascript Object.setPrototypeOf() Object.setPrototypeOf()
=======================
The `Object.setPrototypeOf()` method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](../../operators/null).
**Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to ***any*** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes).
Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](create).
Syntax
------
```
Object.setPrototypeOf(obj, prototype)
```
### Parameters
`obj` The object which is to have its prototype set.
`prototype` The object's new prototype (an object or [`null`](../../operators/null)).
### Return value
The specified object.
### Exceptions
[`TypeError`](../typeerror) Thrown if one of the following conditions is met:
* The `obj` parameter is `undefined` or `null`.
* The `obj` parameter is [non-extensible](isextensible), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype` or [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window). However, the error is not thrown if the new prototype is the same value as the original prototype of `obj`.
* The `prototype` parameter is not an object or [`null`](../../operators/null).
Description
-----------
`Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. You should always use it in favor of the deprecated [`Object.prototype.__proto__`](proto) accessor.
If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing β without coercing it to an object or attempting to set its prototype β and directly returns `obj` as a primitive value. If `prototype` is the same value as the prototype of `obj`, then `obj` is directly returned, without causing a `TypeError` even when `obj` has immutable prototype.
For security concerns, there are certain built-in objects that are designed to have an *immutable prototype*. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. In browsers, [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) and [`location`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) are two other very common examples.
```
Object.isExtensible(Object.prototype); // true; you can add more properties
Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#<Object>' cannot have their prototype set
Object.setPrototypeOf(Object.prototype, null); // No error; the prototype of `Object.prototype` is already `null`
```
Examples
--------
### Pseudoclassical inheritance using Object.setPrototypeOf()
Inheritance in JS using classes.
```
class Human {}
class SuperHero extends Human {}
const superMan = new SuperHero();
```
However, if we want to implement subclasses without using `class`, we can do the following:
```
function Human(name, level) {
this.name = name;
this.level = level;
}
function SuperHero(name, level) {
Human.call(this, name, level);
}
Object.setPrototypeOf(SuperHero.prototype, Human.prototype);
// Set the `[[Prototype]]` of `SuperHero.prototype`
// to `Human.prototype`
// To set the prototypal inheritance chain
Human.prototype.speak = function () {
return `${this.name} says hello.`;
};
SuperHero.prototype.fly = function () {
return `${this.name} is flying.`;
};
const superMan = new SuperHero("Clark Kent", 1);
console.log(superMan.fly());
console.log(superMan.speak());
```
The similarity between classical inheritance (with classes) and pseudoclassical inheritance (with constructors' `prototype` property) as done above is mentioned in [Inheritance chains](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#building_longer_inheritance_chains).
Since function constructors' [`prototype`](../function/prototype) property is writable, you can reassign it to a new object created with [`Object.create()`](create#classical_inheritance_with_object.create) to achieve the same inheritance chain as well. There are caveats to watch out when using `create()`, such as remembering to re-add the [`constructor`](constructor) property.
In the example below, which also uses classes, `SuperHero` is made to inherit from `Human` without using `extends` by using `setPrototypeOf()` instead.
**Warning:** It is not advisable to use `setPrototypeOf()` instead of `extends` due to performance and readability reasons.
```
class Human {}
class SuperHero {}
// Set the instance properties
Object.setPrototypeOf(SuperHero.prototype, Human.prototype);
// Hook up the static properties
Object.setPrototypeOf(SuperHero, Human);
const superMan = new SuperHero();
```
Subclassing without `extends` is mentioned in [ES-6 subclassing](https://hacks.mozilla.org/2015/08/es6-in-depth-subclassing/).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.setprototypeof](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.setprototypeof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 34 | 12 | 31 | 11 | 21 | 9 | 37 | 34 | 31 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Object.setPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Reflect.setPrototypeOf()`](../reflect/setprototypeof)
* [`Object.prototype.isPrototypeOf()`](isprototypeof)
* [`Object.getPrototypeOf()`](getprototypeof)
* [`Object.prototype.__proto__`](proto)
* [Inheritance chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#building_longer_inheritance_chains)
* [ES-6 subclassing](https://hacks.mozilla.org/2015/08/es6-in-depth-subclassing/)
javascript Object.create() Object.create()
===============
The `Object.create()` static method creates a new object, using an existing object as the prototype of the newly created object.
Try it
------
Syntax
------
```
Object.create(proto)
Object.create(proto, propertiesObject)
```
### Parameters
`proto` The object which should be the prototype of the newly-created object.
`propertiesObject` Optional
If specified and not [`undefined`](../undefined), an object whose [enumerable own properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](defineproperties).
### Return value
A new object with the specified prototype object and properties.
### Exceptions
[`TypeError`](../typeerror) Thrown if `proto` is neither [`null`](../../operators/null) nor an [`Object`](../object).
Examples
--------
### Classical inheritance with Object.create()
Below is an example of how to use `Object.create()` to achieve classical inheritance. This is for a single inheritance, which is all that JavaScript supports.
```
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function (x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype, {
// If you don't set Rectangle.prototype.constructor to Rectangle,
// it will take the prototype.constructor of Shape (parent).
// To avoid that, we set the prototype.constructor to Rectangle (child).
constructor: {
value: Rectangle,
enumerable: false,
writable: true,
configurable: true,
},
});
const rect = new Rectangle();
console.log("Is rect an instance of Rectangle?", rect instanceof Rectangle); // true
console.log("Is rect an instance of Shape?", rect instanceof Shape); // true
rect.move(1, 1); // Logs 'Shape moved.'
```
Note that there are caveats to watch out for using `create()`, such as re-adding the [`constructor`](constructor) property to ensure proper semantics. Although `Object.create()` is believed to have better performance than mutating the prototype with [`Object.setPrototypeOf()`](setprototypeof), the difference is in fact negligible if no instances have been created and property accesses haven't been optimized yet. In modern code, the [class](../../classes) syntax should be preferred in any case.
### Using propertiesObject argument with Object.create()
`Object.create()` allows fine-tuned control over the object creation process. The [object initializer syntax](../../operators/object_initializer) is, in fact, a syntax sugar of `Object.create()`. With `Object.create()`, we can create objects with a designated prototype and also some properties. Note that the second parameter maps keys to *property descriptors* β this means you can control each property's enumerability, configurability, etc. as well, which you can't do in object initializers.
```
o = {};
// Is equivalent to:
o = Object.create(Object.prototype);
o = Object.create(Object.prototype, {
// foo is a regular data property
foo: {
writable: true,
configurable: true,
value: "hello",
},
// bar is an accessor property
bar: {
configurable: false,
get() {
return 10;
},
set(value) {
console.log("Setting `o.bar` to", value);
},
},
});
// Create a new object whose prototype is a new, empty
// object and add a single property 'p', with value 42.
o = Object.create({}, { p: { value: 42 } });
```
With `Object.create()`, we can create an object [with `null` as prototype](../object#null-prototype_objects). The equivalent syntax in object initializers would be the [`__proto__`](../../operators/object_initializer#prototype_setter) key.
```
o = Object.create(null);
// Is equivalent to:
o = { \_\_proto\_\_: null };
```
By default properties are *not* writable, enumerable or configurable.
```
o.p = 24; // throws in strict mode
o.p; // 42
o.q = 12;
for (const prop in o) {
console.log(prop);
}
// 'q'
delete o.p;
// false; throws in strict mode
```
To specify a property with the same attributes as in an initializer, explicitly specify `writable`, `enumerable` and `configurable`.
```
o2 = Object.create(
{},
{
p: {
value: 42,
writable: true,
enumerable: true,
configurable: true,
},
},
);
// This is not equivalent to:
// o2 = Object.create({ p: 42 })
// which will create an object with prototype { p: 42 }
```
You can use `Object.create()` to mimic the behavior of the [`new`](../../operators/new) operator.
```
function Constructor() {}
o = new Constructor();
// Is equivalent to:
o = Object.create(Constructor.prototype);
```
Of course, if there is actual initialization code in the `Constructor` function, the `Object.create()` method cannot reflect it.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.create](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.create) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `create` | 5 | 12 | 4 | 9 | 11.6 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.create` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.defineProperty()`](defineproperty)
* [`Object.defineProperties()`](defineproperties)
* [`Object.prototype.isPrototypeOf()`](isprototypeof)
* [`Reflect.construct()`](../reflect/construct)
* John Resig's post on [getPrototypeOf()](https://johnresig.com/blog/objectgetprototypeof/)
javascript Object.keys() Object.keys()
=============
The `Object.keys()` static method returns an array of a given object's own enumerable string-keyed property names.
Try it
------
Syntax
------
```
Object.keys(obj)
```
### Parameters
`obj` An object.
### Return value
An array of strings representing the given object's own enumerable string-keyed property keys.
Description
-----------
`Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a [`for...in`](../../statements/for...in) loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a [`for...in`](../../statements/for...in) loop.
If you need the property values, use [`Object.values()`](values) instead. If you need both the property keys and values, use [`Object.entries()`](entries) instead.
Examples
--------
### Using Object.keys()
```
// Simple array
const arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // ['0', '1', '2']
// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); // ['0', '1', '2']
// Array-like object with random key ordering
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // ['2', '7', '100']
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = 1;
console.log(Object.keys(myObj)); // ['foo']
```
If you want *all* string-keyed own properties, including non-enumerable ones, see [`Object.getOwnPropertyNames()`](getownpropertynames).
### Using Object.keys() on primitives
Non-object arguments are [coerced to objects](../object#object_coercion). Only strings may have own enumerable properties, while all other primitives return an empty array.
```
// Strings have indices as enumerable own properties
console.log(Object.keys("foo")); // ['0', '1', '2']
// Other primitives have no own properties
console.log(Object.keys(100)); // []
```
**Note:** In ES5, passing a non-object to `Object.keys()` threw a [`TypeError`](../typeerror).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.keys](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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` | 5 | 12 | 4 | 9 | 12 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.keys` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.entries()`](entries)
* [`Object.values()`](values)
* [`Object.prototype.propertyIsEnumerable()`](propertyisenumerable)
* [`Object.create()`](create)
* [`Object.getOwnPropertyNames()`](getownpropertynames)
* [`Map.prototype.keys()`](../map/keys)
javascript Object.assign() Object.assign()
===============
The `Object.assign()` static method copies all [enumerable](propertyisenumerable) [own properties](hasown) from one or more *source objects* to a *target object*. It returns the modified target object.
Try it
------
Syntax
------
```
Object.assign(target, ...sources)
```
### Parameters
`target` The target object β what to apply the sources' properties to, which is returned after it is modified.
`sources` The source object(s) β objects containing the properties you want to apply.
### Return value
The target object.
Description
-----------
Properties in the target object are overwritten by properties in the sources if they have the same [key](keys). Later sources' properties overwrite earlier ones.
The `Object.assign()` method only copies *enumerable* and *own* properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](../../functions/get) and [setters](../../functions/set). Therefore it *assigns* properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.
For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) and [`Object.defineProperty()`](defineproperty) instead.
Both [`String`](../string) and [`Symbol`](../symbol) properties are copied.
In case of an error, for example if a property is non-writable, a [`TypeError`](../typeerror) is raised, and the `target` object is changed if any properties are added before the error is raised.
**Note:** `Object.assign()` does not throw on [`null`](../../operators/null) or [`undefined`](../undefined) sources.
Examples
--------
### Cloning an object
```
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
```
### Warning for Deep Clone
For [deep cloning](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy), we need to use alternatives, because `Object.assign()` copies property values.
If the source value is a reference to an object, it only copies the reference value.
```
const obj1 = { a: 0, b: { c: 0 } };
const obj2 = Object.assign({}, obj1);
console.log(obj2); // { a: 0, b: { c: 0 } }
obj1.a = 1;
console.log(obj1); // { a: 1, b: { c: 0 } }
console.log(obj2); // { a: 0, b: { c: 0 } }
obj2.a = 2;
console.log(obj1); // { a: 1, b: { c: 0 } }
console.log(obj2); // { a: 2, b: { c: 0 } }
obj2.b.c = 3;
console.log(obj1); // { a: 1, b: { c: 3 } }
console.log(obj2); // { a: 2, b: { c: 3 } }
// Deep Clone
const obj3 = { a: 0, b: { c: 0 } };
const obj4 = JSON.parse(JSON.stringify(obj3));
obj3.a = 4;
obj3.b.c = 4;
console.log(obj4); // { a: 0, b: { c: 0 } }
```
### Merging objects
```
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
```
### Merging objects with same properties
```
const o1 = { a: 1, b: 1, c: 1 };
const o2 = { b: 2, c: 2 };
const o3 = { c: 3 };
const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
```
The properties are overwritten by other objects that have the same properties later in the parameters order.
### Copying symbol-typed properties
```
const o1 = { a: 1 };
const o2 = { [Symbol('foo')]: 2 };
const obj = Object.assign({}, o1, o2);
console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
```
### Properties on the prototype chain and non-enumerable properties cannot be copied
```
const obj = Object.create({ foo: 1 }, { // foo is on obj's prototype chain.
bar: {
value: 2 // bar is a non-enumerable property.
},
baz: {
value: 3,
enumerable: true // baz is an own enumerable property.
}
});
const copy = Object.assign({}, obj);
console.log(copy); // { baz: 3 }
```
### Primitives will be wrapped to objects
```
const v1 = 'abc';
const v2 = true;
const v3 = 10;
const v4 = Symbol('foo');
const obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// Primitives will be wrapped, null and undefined will be ignored.
// Note, only string wrappers can have own enumerable properties.
console.log(obj); // { "0": "a", "1": "b", "2": "c" }
```
### Exceptions will interrupt the ongoing copying task
```
const target = Object.defineProperty({}, 'foo', {
value: 1,
writable: false
}); // target.foo is a read-only property
Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
// TypeError: "foo" is read-only
// The Exception is thrown when assigning target.foo
console.log(target.bar); // 2, the first source was copied successfully.
console.log(target.foo2); // 3, the first property of the second source was copied successfully.
console.log(target.foo); // 1, exception is thrown here.
console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied.
console.log(target.baz); // undefined, the third source will not be copied either.
```
### Copying accessors
```
const obj = {
foo: 1,
get bar() {
return 2;
}
};
let copy = Object.assign({}, obj);
console.log(copy);
// { foo: 1, bar: 2 }
// The value of copy.bar is obj.bar's getter's return value.
// This is an assign function that copies full descriptors
function completeAssign(target, ...sources) {
sources.forEach((source) => {
const descriptors = Object.keys(source).reduce((descriptors, key) => {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, {});
// By default, Object.assign copies enumerable Symbols, too
Object.getOwnPropertySymbols(source).forEach((sym) => {
const descriptor = Object.getOwnPropertyDescriptor(source, sym);
if (descriptor.enumerable) {
descriptors[sym] = descriptor;
}
});
Object.defineProperties(target, descriptors);
});
return target;
}
copy = completeAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.assign](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `assign` | 45 | 12 | 34 | No | 32 | 9 | 45 | 45 | 34 | 32 | 9 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `Object.assign` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.defineProperties()`](defineproperties)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [Spread in object literals](../../operators/spread_syntax#spread_in_object_literals)
| programming_docs |
javascript Object.prototype.__defineSetter__() Object.prototype.\_\_defineSetter\_\_()
=======================================
**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:** This feature is deprecated in favor of defining [setters](../../functions/set) using the [object initializer syntax](../../operators/object_initializer) or the [`Object.defineProperty()`](defineproperty) API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The `__defineSetter__()` method binds an object's property to a function to be called when an attempt is made to set that property.
Syntax
------
```
\_\_defineSetter\_\_(prop, func)
```
### Parameters
`prop` A string containing the name of the property that the setter `func` is bound to.
`func` A function to be called when there is an attempt to set the specified property. This function receives the following parameter:
`val` The value attempted to be assigned to `prop`.
### Return value
[`undefined`](../undefined).
### Exceptions
[`TypeError`](../typeerror) Thrown if `func` is not a function.
Description
-----------
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `__defineSetter__()` method. This method allows a [setter](../../functions/set) to be defined on a pre-existing object. This is equivalent to [`Object.defineProperty(obj, prop, { set: func, configurable: true, enumerable: true })`](defineproperty), which means the property is enumerable and configurable, and any existing getter, if present, is preserved.
`__defineSetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__defineSetter__()`, it also needs to implement the [`__lookupGetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), [`__lookupSetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__), and [`__defineGetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__) methods.
Examples
--------
### Using \_\_defineSetter\_\_()
```
const o = {};
o.\_\_defineSetter\_\_("value", function (val) {
this.anotherValue = val;
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```
### Defining a setter property in standard ways
You can use the `set` syntax to define a setter when the object is first initialized.
```
const o = {
set value(val) {
this.anotherValue = val;
},
};
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```
You may also use [`Object.defineProperty()`](defineproperty) to define a setter on an object after it's been created. Compared to `__defineSetter__()`, this method allows you to control the setter's enumerability and configurability, as well as defining [symbol](../symbol) properties. The `Object.defineProperty()` method also works with [`null`-prototype objects](../object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__defineSetter__()` method.
```
const o = {};
Object.defineProperty(o, "value", {
set(val) {
this.anotherValue = val;
},
configurable: true,
enumerable: true,
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.\_\_defineSetter\_\_](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-object.prototype.__defineSetter__) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `__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 |
See also
--------
* [Polyfill of `Object.prototype.__defineSetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.prototype.__defineGetter__()`](__definegetter__)
* [`set`](../../functions/set) syntax
* [`Object.defineProperty()`](defineproperty)
* [`Object.prototype.__lookupGetter__()`](__lookupgetter__)
* [`Object.prototype.__lookupSetter__()`](__lookupsetter__)
* [JS Guide: Defining Getters and Setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#defining_getters_and_setters)
* [[Blog Post] Deprecation of \_\_defineGetter\_\_ and \_\_defineSetter\_\_](https://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/)
* [bug 647423](https://bugzilla.mozilla.org/show_bug.cgi?id=647423)
javascript Object() constructor Object() constructor
====================
The `Object` turns the input into an object. Its behavior depends on the input's type.
* If the value is [`null`](../../operators/null) or [`undefined`](../undefined), it creates and returns an empty object.
* Otherwise, it returns an object of a Type that corresponds to the given value.
* If the value is an object already, it returns the value.
Syntax
------
```
new Object(value)
Object(value)
```
**Note:** `Object()` can be called with or without [`new`](../../operators/new). Both create a new object.
### Parameters
`value` Any value.
Examples
--------
### Creating a new Object
```
const o = new Object();
o.foo = 42;
console.log(o);
// { foo: 42 }
```
### Using Object given undefined and null types
The following examples store an empty `Object` object in `o`:
```
const o = new Object();
```
```
const o = new Object(undefined);
```
```
const o = new Object(null);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object-constructor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object-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 |
| `Object` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Object initializer](../../operators/object_initializer)
javascript Object.getOwnPropertySymbols() Object.getOwnPropertySymbols()
==============================
The `Object.getOwnPropertySymbols()` static method returns an array of all symbol properties found directly upon a given object.
Try it
------
Syntax
------
```
Object.getOwnPropertySymbols(obj)
```
### Parameters
`obj` The object whose symbol properties are to be returned.
### Return value
An array of all symbol properties found directly upon the given object.
Description
-----------
Similar to [`Object.getOwnPropertyNames()`](getownpropertynames), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](getownpropertynames) itself does not contain the symbol properties of an object and only the string properties.
As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object.
Examples
--------
### Using getOwnPropertySymbols
```
const obj = {};
const a = Symbol('a');
const b = Symbol.for('b');
obj[a] = 'localSymbol';
obj[b] = 'globalSymbol';
const objectSymbols = Object.getOwnPropertySymbols(obj);
console.log(objectSymbols.length); // 2
console.log(objectSymbols); // [Symbol(a), Symbol(b)]
console.log(objectSymbols[0]); // Symbol(a)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.getownpropertysymbols](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.getownpropertysymbols) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getOwnPropertySymbols` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Object.getOwnPropertySymbols` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`Object.getOwnPropertyNames()`](getownpropertynames)
* [`Symbol`](../symbol)
javascript Object.defineProperties() Object.defineProperties()
=========================
The `Object.defineProperties()` static method defines new or modifies existing properties directly on an object, returning the object.
Try it
------
Syntax
------
```
Object.defineProperties(obj, props)
```
### Parameters
`obj` The object on which to define or modify properties.
`props` An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](defineproperty) for more details).
Data descriptors and accessor descriptors may optionally contain the following keys:
`configurable` `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. `false`
`enumerable` `true` if and only if this property shows up during enumeration of the properties on the corresponding object. `false`
A data descriptor also has the following optional keys:
`value` The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../undefined).**
`writable` `true` if and only if the value associated with the property may be changed with an [assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators). `false`
An accessor descriptor also has the following optional keys:
`get` A function which serves as a getter for the property, or [`undefined`](../undefined) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../undefined).**
`set` A function which serves as a setter for the property, or [`undefined`](../undefined) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../undefined).**
If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown.
### Return value
The object that was passed to the function.
Examples
--------
### Using Object.defineProperties
```
const obj = {};
Object.defineProperties(obj, {
'property1': {
value: true,
writable: true
},
'property2': {
value: 'Hello',
writable: false
}
// etc. etc.
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.defineproperties](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.defineproperties) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `defineProperties` | 5 | 12 | 4 | 9 | 11.6 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.defineProperties` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.defineProperty()`](defineproperty)
* [`Object.keys()`](keys)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
javascript Object.getOwnPropertyDescriptors() Object.getOwnPropertyDescriptors()
==================================
The `Object.getOwnPropertyDescriptors()` static method returns all own property descriptors of a given object.
Try it
------
Syntax
------
```
Object.getOwnPropertyDescriptors(obj)
```
### Parameters
`obj` The object for which to get all own property descriptors.
### Return value
An object containing all own property descriptors of an object. Might be an empty object, if there are no properties.
Description
-----------
This method permits examination of the precise description of all own properties of an object. A *property* in JavaScript consists of either a string-valued name or a [`Symbol`](../symbol) and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](defineproperty).
A *property descriptor* is a record with some of the following attributes:
`value` The value associated with the property (data descriptors only).
`writable` `true` if and only if the value associated with the property may be changed (data descriptors only).
`get` A function which serves as a getter for the property, or [`undefined`](../undefined) if there is no getter (accessor descriptors only).
`set` A function which serves as a setter for the property, or [`undefined`](../undefined) if there is no setter (accessor descriptors only).
`configurable` `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
`enumerable` `true` if and only if this property shows up during enumeration of the properties on the corresponding object.
Examples
--------
### Creating a shallow copy
Whereas the [`Object.assign()`](assign) method will only copy enumerable and own properties from a source object to a target object, you are able to use this method and [`Object.create()`](create) for a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) between two unknown objects:
```
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
);
```
### Creating a subclass
A typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. This can get awkward especially for getters and setters. Instead, you can use this code to set the prototype:
```
function superclass() {}
superclass.prototype = {
// Define the superclass constructor, methods, and properties here
};
function subclass() {}
subclass.prototype = Object.create(
superclass.prototype,
{
// Define the subclass constructor, methods, and properties here
}
);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.getownpropertydescriptors](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.getownpropertydescriptors) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getOwnPropertyDescriptors` | 54 | 15 | 50 | No | 41 | 10 | 54 | 54 | 50 | 41 | 10 | 6.0 | 1.0 | 7.0.0
6.5.0 |
See also
--------
* [Polyfill of `Object.getOwnPropertyDescriptors` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor)
* [`Object.defineProperty()`](defineproperty)
* [Polyfill](https://github.com/tc39/proposal-object-getownpropertydescriptors)
javascript Object.preventExtensions() Object.preventExtensions()
==========================
The `Object.preventExtensions()` static method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned.
Try it
------
Syntax
------
```
Object.preventExtensions(obj)
```
### Parameters
`obj` The object which should be made non-extensible.
### Return value
The object being made non-extensible.
Description
-----------
An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be *deleted*. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](../../strict_mode), throwing a [`TypeError`](../typeerror).
Unlike [`Object.seal()`](seal) and [`Object.freeze()`](freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](../reflect/preventextensions).
`Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype.
This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable.
There is no way to make an object extensible again once it has been made non-extensible.
Examples
--------
### Using Object.preventExtensions
```
// Object.preventExtensions returns the object
// being made non-extensible.
const obj = {};
const obj2 = Object.preventExtensions(obj);
obj === obj2; // true
// Objects are extensible by default.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Object.defineProperty throws when adding
// a new property to a non-extensible object.
const nonExtensible = { removable: true };
Object.preventExtensions(nonExtensible);
Object.defineProperty(nonExtensible, 'new', {
value: 8675309
}); // throws a TypeError
// In strict mode, attempting to add new properties
// to a non-extensible object throws a TypeError.
function fail() {
'use strict';
// throws a TypeError
nonExtensible.newProperty = 'FAIL';
}
fail();
```
A non-extensible object's prototype is immutable:
```
const fixed = Object.preventExtensions({});
// throws a 'TypeError'.
fixed.__proto__ = { oh: 'hai' };
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.
```
Object.preventExtensions(1);
// TypeError: 1 is not an object (ES5 code)
Object.preventExtensions(1);
// 1 (ES2015 code)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.preventextensions](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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 |
| `ES2015_behavior` | 44 | 12 | 35 | 11 | 31 | 9 | 44 | 44 | 35 | 32 | 9 | 4.0 | 1.0 | 4.0.0 |
| `preventExtensions` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.isExtensible()`](isextensible)
* [`Object.seal()`](seal)
* [`Object.isSealed()`](issealed)
* [`Object.freeze()`](freeze)
* [`Object.isFrozen()`](isfrozen)
* [`Reflect.preventExtensions()`](../reflect/preventextensions)
| programming_docs |
javascript Object.isExtensible() Object.isExtensible()
=====================
The `Object.isExtensible()` static method determines if an object is extensible (whether it can have new properties added to it).
Try it
------
Syntax
------
```
Object.isExtensible(obj)
```
### Parameters
`obj` The object which should be checked.
### Return value
A [`Boolean`](../boolean) indicating whether or not the given object is extensible.
Description
-----------
Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](preventextensions), [`Object.seal()`](seal), [`Object.freeze()`](freeze), or [`Reflect.preventExtensions()`](../reflect/preventextensions).
Examples
--------
### Using Object.isExtensible
```
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // false
// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // false
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, it will return `false` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.
```
Object.isExtensible(1);
// TypeError: 1 is not an object (ES5 code)
Object.isExtensible(1);
// false (ES2015 code)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.isextensible](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.preventExtensions()`](preventextensions)
* [`Object.seal()`](seal)
* [`Object.isSealed()`](issealed)
* [`Object.freeze()`](freeze)
* [`Object.isFrozen()`](isfrozen)
* [`Reflect.isExtensible()`](../reflect/isextensible)
javascript Object.prototype.isPrototypeOf() Object.prototype.isPrototypeOf()
================================
The `isPrototypeOf()` method checks if an object exists in another object's prototype chain.
**Note:** `isPrototypeOf()` differs from the [`instanceof`](../../operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself.
Try it
------
Syntax
------
```
isPrototypeOf(object)
```
### Parameters
`object` The object whose prototype chain will be searched.
### Return value
A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive).
### Errors thrown
[`TypeError`](../typeerror) Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](../object#object_coercion)).
Description
-----------
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](../object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found.
Examples
--------
### Using isPrototypeOf()
This example demonstrates that `Baz.prototype`, `Bar.prototype`, `Foo.prototype` and `Object.prototype` exist in the prototype chain for object `baz`:
```
class Foo {}
class Bar extends Foo {}
class Baz extends Bar {}
const foo = new Foo();
const bar = new Bar();
const baz = new Baz();
// prototype chains:
// foo: Foo --> Object
// bar: Bar --> Foo --> Object
// baz: Baz --> Bar --> Foo --> Object
console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Baz.prototype.isPrototypeOf(bar)); // false
console.log(Baz.prototype.isPrototypeOf(foo)); // false
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(foo)); // false
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(bar)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true
```
The `isPrototypeOf()` method β along with the [`instanceof`](../../operators/instanceof) operator β comes in particularly handy if you have code that can only function when dealing with objects descended from a specific prototype chain; e.g., to guarantee that certain methods or properties will be present on that object.
For example, to execute some code that's only safe to run if a `baz` object has `Foo.prototype` in its prototype chain, you can do this:
```
if (Foo.prototype.isPrototypeOf(baz)) {
// do something safe
}
```
However, `Foo.prototype` existing in `baz`'s prototype chain doesn't imply `baz` was created using `Foo` as its constructor. For example, `baz` could be directly assigned with `Foo.prototype` as its prototype. In this case, if your code reads [private fields](../../classes/private_class_fields) of `Foo` from `baz`, it would still fail:
```
class Foo {
#value = "foo";
static getValue(x) {
return x.#value;
}
}
const baz = { \_\_proto\_\_: Foo.prototype };
if (Foo.prototype.isPrototypeOf(baz)) {
console.log(Foo.getValue(baz)); // TypeError: Cannot read private member #value from an object whose class did not declare it
}
```
The same applies to [`instanceof`](../../operators/instanceof). If you need to read private fields in a secure way, offer a branded check method using [`in`](../../operators/in) instead.
```
class Foo {
#value = "foo";
static getValue(x) {
return x.#value;
}
static isFoo(x) {
return #value in x;
}
}
const baz = { \_\_proto\_\_: Foo.prototype };
if (Foo.isFoo(baz)) {
// Doesn't run, because baz is not a Foo
console.log(Foo.getValue(baz));
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.isprototypeof](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.prototype.isprototypeof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isPrototypeOf` | 1 | 12 | 1 | 9 | 4 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`instanceof`](../../operators/instanceof)
* [`Object.getPrototypeOf()`](getprototypeof)
* [`Object.setPrototypeOf()`](setprototypeof)
* [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
javascript Object.isSealed() Object.isSealed()
=================
The `Object.isSealed()` static method determines if an object is sealed.
Try it
------
Syntax
------
```
Object.isSealed(obj)
```
### Parameters
`obj` The object which should be checked.
### Return value
A [`Boolean`](../boolean) indicating whether or not the given object is sealed.
Description
-----------
Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](isextensible) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable).
Examples
--------
### Using Object.isSealed
```
// Objects aren't sealed by default.
const empty = {};
Object.isSealed(empty); // false
// If you make an empty object non-extensible,
// it is vacuously sealed.
Object.preventExtensions(empty);
Object.isSealed(empty); // true
// The same is not true of a non-empty object,
// unless its properties are all non-configurable.
const hasProp = { fee: 'fie foe fum' };
Object.preventExtensions(hasProp);
Object.isSealed(hasProp); // false
// But make them all non-configurable
// and the object becomes sealed.
Object.defineProperty(hasProp, 'fee', {
configurable: false
});
Object.isSealed(hasProp); // true
// The easiest way to seal an object, of course,
// is Object.seal.
const sealed = {};
Object.seal(sealed);
Object.isSealed(sealed); // true
// A sealed object is, by definition, non-extensible.
Object.isExtensible(sealed); // false
// A sealed object might be frozen,
// but it doesn't have to be.
Object.isFrozen(sealed); // true
// (all properties also non-writable)
const s2 = Object.seal({ p: 3 });
Object.isFrozen(s2); // false
// ('p' is still writable)
const s3 = Object.seal({ get p() { return 0; } });
Object.isFrozen(s3); // true
// (only configurability matters for accessor properties)
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, it will return `true` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.
```
Object.isSealed(1);
// TypeError: 1 is not an object (ES5 code)
Object.isSealed(1);
// true (ES2015 code)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.issealed](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.issealed) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isSealed` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.seal()`](seal)
* [`Object.preventExtensions()`](preventextensions)
* [`Object.isExtensible()`](isextensible)
* [`Object.freeze()`](freeze)
* [`Object.isFrozen()`](isfrozen)
javascript Object.getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor()
=================================
The `Object.getOwnPropertyDescriptor()` static method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration.
Try it
------
Syntax
------
```
Object.getOwnPropertyDescriptor(obj, prop)
```
### Parameters
`obj` The object in which to look for the property.
`prop` The name or [`Symbol`](../symbol) of the property whose description is to be retrieved.
### Return value
A property descriptor of the given property if it exists on the object, [`undefined`](../undefined) otherwise.
Description
-----------
This method permits examination of the precise description of a property. A *property* in JavaScript consists of either a string-valued name or a [`Symbol`](../symbol) and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](defineproperty).
A *property descriptor* is a record with some of the following attributes:
`value` The value associated with the property (data descriptors only).
`writable` `true` if and only if the value associated with the property may be changed (data descriptors only).
`get` A function which serves as a getter for the property, or [`undefined`](../undefined) if there is no getter (accessor descriptors only).
`set` A function which serves as a setter for the property, or [`undefined`](../undefined) if there is no setter (accessor descriptors only).
`configurable` `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
`enumerable` `true` if and only if this property shows up during enumeration of the properties on the corresponding object.
Examples
--------
### Using Object.getOwnPropertyDescriptor
```
let o, d;
o = { get foo() { return 17; } };
d = Object.getOwnPropertyDescriptor(o, 'foo');
console.log(d);
// {
// configurable: true,
// enumerable: true,
// get: [Function: get foo],
// set: undefined
// }
o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, 'bar');
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 42,
// writable: true
// }
o = { [Symbol.for('baz')]: 73 }
d = Object.getOwnPropertyDescriptor(o, Symbol.for('baz'));
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 73,
// writable: true
// }
o = {};
Object.defineProperty(o, 'qux', {
value: 8675309,
writable: false,
enumerable: false
});
d = Object.getOwnPropertyDescriptor(o, 'qux');
console.log(d);
// {
// value: 8675309,
// writable: false,
// enumerable: false,
// configurable: false
// }
```
### Non-object coercion
In ES5, if the first argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, a non-object first argument will be coerced to an object at first.
```
Object.getOwnPropertyDescriptor('foo', 0);
// TypeError: "foo" is not an object // ES5 code
Object.getOwnPropertyDescriptor('foo', 0);
// Object returned by ES2015 code: {
// configurable: false,
// enumerable: true,
// value: "f",
// writable: false
// }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.getownpropertydescriptor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.getownpropertydescriptor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 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 |
See also
--------
* [`Object.defineProperty()`](defineproperty)
* [`Reflect.getOwnPropertyDescriptor()`](../reflect/getownpropertydescriptor)
javascript Object.prototype.__proto__ Object.prototype.\_\_proto\_\_
==============================
**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.
**Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `obj.__proto__ = ...` statement, but may extend to ***any*** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes).
**Note:** The use of `__proto__` is controversial and discouraged. Its existence and exact behavior have only been standardized as a legacy feature to ensure web compatibility, while it presents several security issues and footguns. For better support, prefer [`Object.getPrototypeOf()`](getprototypeof)/[`Reflect.getPrototypeOf()`](../reflect/getprototypeof) and [`Object.setPrototypeOf()`](setprototypeof)/[`Reflect.setPrototypeOf()`](../reflect/setprototypeof) instead.
The `__proto__` accessor property of `Object.prototype` exposes the [`[[Prototype]]`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) (either an object or [`null`](../../operators/null)) of this object.
The `__proto__` property can also be used in an object literal definition to set the object `[[Prototype]]` on creation, as an alternative to [`Object.create()`](create). See: [object initializer / literal syntax](../../operators/object_initializer). That syntax is standard and optimized for in implementations, and quite different from `Object.prototype.__proto__`.
Syntax
------
```
obj.__proto__
```
### Return value
If used as a getter, returns the object's `[[Prototype]]`.
### Exceptions
[`TypeError`](../typeerror) Thrown if attempting to set the prototype of a [non-extensible](isextensible) object or an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype` or [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window).
Description
-----------
The `__proto__` getter function exposes the value of the internal `[[Prototype]]` of an object. For objects created using an object literal, this value is `Object.prototype`. For objects created using array literals, this value is [`Array.prototype`](../array). For functions, this value is [`Function.prototype`](../function/prototype). You can read more about the prototype chain in [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
The `__proto__` setter allows the `[[Prototype]]` of an object to be mutated. The value provided must be an object or [`null`](../../operators/null). Providing any other value will do nothing.
Unlike [`Object.getPrototypeOf()`](getprototypeof) and [`Object.setPrototypeOf()`](setprototypeof), which are always available on `Object` as static properties and always reflect the `[[Prototype]]` internal property, the `__proto__` property doesn't always exist as a property on all objects, and as a result doesn't reflect `[[Prototype]]` reliably.
The `__proto__` property is a simple accessor property on `Object.prototype` consisting of a getter and setter function. A property access for `__proto__` that eventually consults `Object.prototype` will find this property, but an access that does not consult `Object.prototype` will not. If some other `__proto__` property is found before `Object.prototype` is consulted, that property will hide the one found on `Object.prototype`.
[`null`-prototype objects](../object#null-prototype_objects) don't inherit any property from `Object.prototype`, including the `__proto__` accessor property, so if you try to read `__proto__` on such an object, the value is always `undefined` regardless of the object's actual `[[Prototype]]`, and any assignment to `__proto__` would create a new property called `__proto__` instead of setting the object's prototype. Furthermore, `__proto__` can be redefined as an own property on any object instance through [`Object.defineProperty()`](defineproperty) without triggering the setter. In this case, `__proto__` will no longer be an accessor for `[[Prototype]]`. Therefore, always prefer [`Object.getPrototypeOf()`](getprototypeof) and [`Object.setPrototypeOf()`](setprototypeof) for setting and getting the `[[Prototype]]` of an object.
Examples
--------
### Using \_\_proto\_\_
```
function Circle() {}
const shape = {};
const circle = new Circle();
// Set the object prototype.
// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.
shape.__proto__ = circle;
// Get the object prototype
console.log(shape.__proto__ === Circle); // false
```
```
const ShapeA = function () {};
const ShapeB = {
a() {
console.log("aaa");
},
};
ShapeA.prototype.__proto__ = ShapeB;
console.log(ShapeA.prototype.__proto__); // { a: [Function: a] }
const shapeA = new ShapeA();
shapeA.a(); // aaa
console.log(ShapeA.prototype === shapeA.__proto__); // true
```
```
const ShapeC = function () {};
const ShapeD = {
a() {
console.log("a");
},
};
const shapeC = new ShapeC();
shapeC.__proto__ = ShapeD;
shapeC.a(); // a
console.log(ShapeC.prototype === shapeC.__proto__); // false
```
```
function Test() {}
Test.prototype.myName = function () {
console.log("myName");
};
const test = new Test();
console.log(test.__proto__ === Test.prototype); // true
test.myName(); // myName
const obj = {};
obj.__proto__ = Test.prototype;
obj.myName(); // myName
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.\_\_proto\_\_](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.prototype.__proto__) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `proto` | 1 | 12 | 1 | 11 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 | No | 0.10.0 |
See also
--------
* [`Object.prototype.isPrototypeOf()`](isprototypeof)
* [`Object.getPrototypeOf()`](getprototypeof)
* [`Object.setPrototypeOf()`](setprototypeof)
| programming_docs |
javascript Object.prototype.__defineGetter__() Object.prototype.\_\_defineGetter\_\_()
=======================================
**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:** This feature is deprecated in favor of defining [getters](../../functions/get) using the [object initializer syntax](../../operators/object_initializer) or the [`Object.defineProperty()`](defineproperty) API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The `__defineGetter__()` method binds an object's property to a function to be called when that property is looked up.
Syntax
------
```
\_\_defineGetter\_\_(prop, func)
```
### Parameters
`prop` A string containing the name of the property that the getter `func` is bound to.
`func` A function to be bound to a lookup of the specified property.
### Return value
[`undefined`](../undefined).
### Exceptions
[`TypeError`](../typeerror) Thrown if `func` is not a function.
Description
-----------
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `__defineGetter__()` method. This method allows a [getter](../../functions/get) to be defined on a pre-existing object. This is equivalent to [`Object.defineProperty(obj, prop, { get: func, configurable: true, enumerable: true })`](defineproperty), which means the property is enumerable and configurable, and any existing setter, if present, is preserved.
`__defineGetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__defineGetter__()`, it also needs to implement the [`__lookupGetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), [`__lookupSetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__), and [`__defineSetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__) methods.
Examples
--------
### Using \_\_defineGetter\_\_()
```
const o = {};
o.\_\_defineGetter\_\_("gimmeFive", function () {
return 5;
});
console.log(o.gimmeFive); // 5
```
### Defining a getter property in standard ways
You can use the `get` syntax to define a getter when the object is first initialized.
```
const o = {
get gimmeFive() {
return 5;
},
};
console.log(o.gimmeFive); // 5
```
You may also use [`Object.defineProperty()`](defineproperty) to define a getter on an object after it's been created. Compared to `__defineGetter__()`, this method allows you to control the getter's enumerability and configurability, as well as defining [symbol](../symbol) properties. The `Object.defineProperty()` method also works with [`null`-prototype objects](../object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__defineGetter__()` method.
```
const o = {};
Object.defineProperty(o, "gimmeFive", {
get() {
return 5;
},
configurable: true,
enumerable: true,
});
console.log(o.gimmeFive); // 5
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.\_\_defineGetter\_\_](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-object.prototype.__defineGetter__) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `__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 |
See also
--------
* [Polyfill of `Object.prototype.__defineGetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.prototype.__defineSetter__()`](__definesetter__)
* [`get`](../../functions/get) syntax
* [`Object.defineProperty()`](defineproperty)
* [`Object.prototype.__lookupGetter__()`](__lookupgetter__)
* [`Object.prototype.__lookupSetter__()`](__lookupsetter__)
* [JS Guide: Defining Getters and Setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#defining_getters_and_setters)
* [[Blog Post] Deprecation of \_\_defineGetter\_\_ and \_\_defineSetter\_\_](https://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/)
* [bug 647423](https://bugzilla.mozilla.org/show_bug.cgi?id=647423)
javascript Object.seal() Object.seal()
=============
The `Object.seal()` static method *seals* an object. Sealing an object [prevents extensions](preventextensions) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in.
Try it
------
Syntax
------
```
Object.seal(obj)
```
### Parameters
`obj` The object which should be sealed.
### Return value
The object being sealed.
Description
-----------
Sealing an object is equivalent to [preventing extensions](preventextensions) and then changing all existing [properties' descriptors](defineproperty#description) to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../typeerror) (most commonly, although not exclusively, when in [strict mode](../../strict_mode) code).
The prototype chain remains untouched. However, due to the effect of [preventing extensions](preventextensions), the `[[Prototype]]` cannot be reassigned.
Unlike [`Object.freeze()`](freeze), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable.
Examples
--------
### Using Object.seal
```
const obj = {
prop() {},
foo: 'bar'
};
// New properties may be added, existing properties
// may be changed or removed.
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;
const o = Object.seal(obj);
o === obj; // true
Object.isSealed(obj); // true
// Changing property values on a sealed object
// still works.
obj.foo = 'quux';
// But you can't convert data properties to accessors,
// or vice versa.
Object.defineProperty(obj, 'foo', {
get() { return 'g'; }
}); // throws a TypeError
// Now any changes, other than to property values,
// will fail.
obj.quaxxor = 'the friendly duck';
// silently doesn't add the property
delete obj.foo;
// silently doesn't delete the property
// ...and in strict mode such attempts
// will throw TypeErrors.
function fail() {
'use strict';
delete obj.foo; // throws a TypeError
obj.sparky = 'arf'; // throws a TypeError
}
fail();
// Attempted additions through
// Object.defineProperty will also throw.
Object.defineProperty(obj, 'ohai', {
value: 17
}); // throws a TypeError
Object.defineProperty(obj, 'foo', {
value: 'eit'
}); // changes existing property value
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.
```
Object.seal(1);
// TypeError: 1 is not an object (ES5 code)
Object.seal(1);
// 1 (ES2015 code)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.seal](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.seal) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `seal` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.isSealed()`](issealed)
* [`Object.preventExtensions()`](preventextensions)
* [`Object.isExtensible()`](isextensible)
* [`Object.freeze()`](freeze)
* [`Object.isFrozen()`](isfrozen)
javascript Object.entries() Object.entries()
================
The `Object.entries()` static method returns an array of a given object's own enumerable string-keyed property key-value pairs.
Try it
------
Syntax
------
```
Object.entries(obj)
```
### Parameters
`obj` An object.
### Return value
An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value.
Description
-----------
`Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a [`for...in`](../../statements/for...in) loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a [`for...in`](../../statements/for...in) loop.
If you only need the property keys, use [`Object.keys()`](keys) instead. If you only need the property values, use [`Object.values()`](values) instead.
Examples
--------
### Using Object.entries()
```
const obj = { foo: "bar", baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
// Array-like object with random key ordering
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = "bar";
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]
```
### Using Object.entries() on primitives
Non-object arguments are [coerced to objects](../object#object_coercion). Only strings may have own enumerable properties, while all other primitives return an empty array.
```
// Strings have indices as enumerable own properties
console.log(Object.entries("foo")); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]
// Other primitives have no own properties
console.log(Object.entries(100)); // []
```
### Converting an Object to a Map
The [`Map()`](../map/map) constructor accepts an iterable of `entries`. With `Object.entries`, you can easily convert from [`Object`](../object) to [`Map`](../map):
```
const obj = { foo: "bar", baz: 42 };
const map = new Map(Object.entries(obj));
console.log(map); // Map(2) {"foo" => "bar", "baz" => 42}
```
### Iterating through an Object
Using [array destructuring](../../operators/destructuring_assignment#array_destructuring), you can iterate through objects easily.
```
// Using for...of loop
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key}${value}`); // "a 5", "b 7", "c 9"
}
// Using array methods
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}${value}`); // "a 5", "b 7", "c 9"
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.entries](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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` | 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
--------
* [Polyfill of `Object.entries` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.keys()`](keys)
* [`Object.values()`](values)
* [`Object.prototype.propertyIsEnumerable()`](propertyisenumerable)
* [`Object.create()`](create)
* [`Object.fromEntries()`](fromentries)
* [`Object.getOwnPropertyNames()`](getownpropertynames)
* [`Map.prototype.entries()`](../map/entries)
javascript Object.getPrototypeOf() Object.getPrototypeOf()
=======================
The `Object.getPrototypeOf()` static method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object.
Try it
------
Syntax
------
```
Object.getPrototypeOf(obj)
```
### Parameters
`obj` The object whose prototype is to be returned.
### Return value
The prototype of the given object, which may be [`null`](../../operators/null).
Examples
--------
### Using getPrototypeOf
```
const proto = {};
const obj = Object.create(proto);
Object.getPrototypeOf(obj) === proto; // true
```
### Non-object coercion
In ES5, it will throw a [`TypeError`](../typeerror) exception if the `obj` parameter isn't an object. In ES2015, the parameter will be coerced to an [`Object`](../object).
```
Object.getPrototypeOf('foo');
// TypeError: "foo" is not an object (ES5 code)
Object.getPrototypeOf('foo');
// String.prototype (ES2015 code)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.getprototypeof](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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` | 5 | 12 | 3.5 | 9 | 12.1 | 5 | 4.4 | 18 | 4 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.getPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.prototype.isPrototypeOf()`](isprototypeof)
* [`Object.setPrototypeOf()`](setprototypeof)
* [`Object.prototype.__proto__`](proto)
* John Resig's post on [getPrototypeOf](https://johnresig.com/blog/objectgetprototypeof/)
* [`Reflect.getPrototypeOf()`](../reflect/getprototypeof)
javascript Object.prototype.hasOwnProperty() Object.prototype.hasOwnProperty()
=================================
The `hasOwnProperty()` method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
Try it
------
**Note:** [`Object.hasOwn()`](hasown) is recommended over `hasOwnProperty()`, in browsers where it is supported.
Syntax
------
```
hasOwnProperty(prop)
```
### Parameters
`prop` The [`String`](../string) name or [Symbol](../symbol) of the property to test.
### Return value
Returns `true` if the object has the specified property as own property; `false` otherwise.
Description
-----------
The `hasOwnProperty()` method returns `true` if the specified property is a direct property of the object β even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the [`in`](../../operators/in) operator, this method does not check for the specified property in the object's prototype chain.
The method can be called on *most* JavaScript objects, because most objects descend from [`Object`](../object), and hence inherit its methods. For example [`Array`](../array) is an [`Object`](../object), so you can use `hasOwnProperty()` method to check whether an index exists:
```
const fruits = ['Apple', 'Banana','Watermelon', 'Orange'];
fruits.hasOwnProperty(3); // true ('Orange')
fruits.hasOwnProperty(4); // false - not defined
```
The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below.
Examples
--------
### Using hasOwnProperty to test for an own property's existence
The following code shows how to determine whether the `example` object contains a property named `prop`.
```
const example = {};
example.hasOwnProperty('prop'); // false
example.prop = 'exists';
example.hasOwnProperty('prop'); // true - 'prop' has been defined
example.prop = null;
example.hasOwnProperty('prop'); // true - own property exists with value of null
example.prop = undefined;
example.hasOwnProperty('prop'); // true - own property exists with value of undefined
```
### Direct vs. inherited properties
The following example differentiates between direct properties and properties inherited through the prototype chain:
```
const example = {};
example.prop = 'exists';
// `hasOwnProperty` will only return true for direct properties:
example.hasOwnProperty('prop'); // returns true
example.hasOwnProperty('toString'); // returns false
example.hasOwnProperty('hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in example; // returns true
'toString' in example; // returns true
'hasOwnProperty' in example; // returns true
```
### Iterating over the properties of an object
The following example shows how to iterate over the enumerable properties of an object without executing on inherited properties.
```
const buz = {
fog: 'stack',
};
for (const name in buz) {
if (buz.hasOwnProperty(name)) {
console.log(`this is fog (${name}) for sure. Value: ${buz[name]}`);
} else {
console.log(name); // toString or something else
}
}
```
Note that the [`for...in`](../../statements/for...in) loop only iterates enumerable items: the absence of non-enumerable properties emitted from the loop does not imply that `hasOwnProperty` itself is confined strictly to enumerable items (as with [`Object.getOwnPropertyNames()`](getownpropertynames)).
### Using hasOwnProperty as a property name
JavaScript does not protect the property name `hasOwnProperty`; an object that has a property with this name may return incorrect results:
```
const foo = {
hasOwnProperty() {
return false;
},
bar: 'Here be dragons',
};
foo.hasOwnProperty('bar'); // reimplementation always returns false
```
The recommended way to overcome this problem is to instead use [`Object.hasOwn()`](hasown) (in browsers that support it). Other alternatives include using an *external* `hasOwnProperty`:
```
const foo = { bar: 'Here be dragons' };
// Use Object.hasOwn() method - recommended
Object.hasOwn(foo, "bar"); // true
// Use the hasOwnProperty property from the Object prototype
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
// Use another Object's hasOwnProperty
// and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true
```
Note that in the first two cases there are no newly created objects.
### Objects created with Object.create(null)
Objects created using [`Object.create(null)`](create) do not inherit from `Object.prototype`, making `hasOwnProperty()` inaccessible.
```
const foo = Object.create(null);
foo.prop = 'exists';
foo.hasOwnProperty("prop"); // Uncaught TypeError: foo.hasOwnProperty is not a function
```
The solutions in this case are the same as for the previous section: use [`Object.hasOwn()`](hasown) by preference, otherwise use an external object's `hasOwnProperty()`.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.hasownproperty](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.prototype.hasownproperty) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `hasOwnProperty` | 1 | 12 | 1 | 5.5 | 5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.hasOwn()`](hasown)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.getOwnPropertyNames()`](getownpropertynames)
* [`for...in`](../../statements/for...in)
* [`in`](../../operators/in)
* [JavaScript Guide: Inheritance revisited](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
| programming_docs |
javascript Object.prototype.toString() Object.prototype.toString()
===========================
The `toString()` method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion) logic.
Try it
------
Syntax
------
```
toString()
```
### Parameters
By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../number/tostring) and [`BigInt.prototype.toString()`](../bigint/tostring) methods take an optional `radix` parameter.
### Return value
A string representing the object.
Description
-----------
JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
This method is called in priority by [string conversion](../string#string_coercion), but [numeric conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](valueof) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString()`](../array/tostring) method returns `"1"`, which is then converted to a number.
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`@@toPrimitive`](../symbol/toprimitive) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion.
To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../function/call) or [`Function.prototype.apply()`](../function/apply) on it, passing the object you want to inspect as the first parameter (called `thisArg`).
```
const arr = [1, 2, 3];
arr.toString(); // "1,2,3"
Object.prototype.toString.call(arr); // "[object Array]"
```
`Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../symbol/tostringtag) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](../map) and [`Symbol`](../symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below):
* [`Array`](../array)
* [`Function`](../../functions) (anything whose [`typeof`](../../operators/typeof) returns `"function"`)
* [`Error`](../error)
* [`Boolean`](../boolean)
* [`Number`](../number)
* [`String`](../string)
* [`Date`](../date)
* [`RegExp`](../regexp)
The [`arguments`](../../functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`.
`Object.prototype.toString()` invoked on [`null`](../../operators/null) and [`undefined`](../undefined) returns `[object Null]` and `[object Undefined]`, respectively.
Examples
--------
### Overriding toString for custom objects
You can create a function to be called in place of the default `toString()` method. The `toString()` function you create should return a string value. If it returns an object and the method is called implicitly during [type conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion), then its result is ignored and the value of a related method, [`valueOf()`](valueof), is used instead, or a `TypeError` is thrown if none of these methods return a primitive.
The following code defines a `Dog` class.
```
class Dog {
constructor(name, breed, color, sex) {
this.name = name;
this.breed = breed;
this.color = color;
this.sex = sex;
}
}
```
If you call the `toString()` method, either explicitly or implicitly, on an instance of `Dog`, it returns the default value inherited from [`Object`](../object):
```
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");
theDog.toString(); // "[object Object]"
`${theDog}`; // "[object Object]"
```
The following code overrides the default `toString()` method. This method generates a string containing the `name`, `breed`, `color`, and `sex` of the object.
```
class Dog {
constructor(name, breed, color, sex) {
this.name = name;
this.breed = breed;
this.color = color;
this.sex = sex;
}
toString() {
return `Dog ${this.name} is a ${this.sex}${this.color}${this.breed}`;
}
}
```
With the preceding code in place, any time an instance of `Dog` is used in a string context, JavaScript automatically calls the `toString()` method.
```
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");
`${theDog}`; // "Dog Gabby is a female chocolate Lab"
```
### Using toString() to detect object class
`toString()` can be used with every object and (by default) allows you to get its class.
```
const toString = Object.prototype.toString;
toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
```
Using `toString()` in this way is unreliable; objects can change the behavior of `Object.prototype.toString()` by defining a [`Symbol.toStringTag`](../symbol/tostringtag) property, leading to unexpected results. For example:
```
const myDate = new Date();
Object.prototype.toString.call(myDate); // [object Date]
myDate[Symbol.toStringTag] = "myDate";
Object.prototype.toString.call(myDate); // [object myDate]
Date.prototype[Symbol.toStringTag] = "prototype polluted";
Object.prototype.toString.call(new Date()); // [object prototype polluted]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.tostring](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.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 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.prototype.toString` with `Symbol.toStringTag` support in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.prototype.valueOf()`](valueof)
* [`Number.prototype.toString()`](../number/tostring)
* [`Symbol.toPrimitive`](../symbol/toprimitive)
* [`Symbol.toStringTag`](../symbol/tostringtag)
javascript Object.defineProperty() Object.defineProperty()
=======================
The `Object.defineProperty()` static method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Try it
------
Syntax
------
```
Object.defineProperty(obj, prop, descriptor)
```
### Parameters
`obj` The object on which to define the property.
`prop` The name or [`Symbol`](../symbol) of the property to be defined or modified.
`descriptor` The descriptor for the property being defined or modified.
### Return value
The object that was passed to the function.
Description
-----------
This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration ([`for...in`](../../statements/for...in) loop or [`Object.keys`](keys) method), whose values may be changed, and which may be [deleted](../../operators/delete). This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable.
Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.
Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`):
`configurable` when this is set to `false`,
* the type of this property cannot be changed between data property and accessor property, and
* the property may not be deleted, and
* other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`).
`false`
`enumerable` `true` if and only if this property shows up during enumeration of the properties on the corresponding object. `false`
A **data descriptor** also has the following optional keys:
`value` The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../undefined).**
`writable` `true` if the value associated with the property may be changed with an [assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators). `false`
An **accessor descriptor** also has the following optional keys:
`get` A function which serves as a getter for the property, or [`undefined`](../undefined) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../undefined).**
`set` A function which serves as a setter for the property, or [`undefined`](../undefined) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../undefined).**
If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both [`value` or `writable`] and [`get` or `set`] keys, an exception is thrown.
Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](../../operators/null) with [`Object.create(null)`](create).
```
const obj = {};
// 1. Using a null prototype: no inherited properties
const descriptor = Object.create(null);
descriptor.value = 'static';
// not enumerable, not configurable, not writable as defaults
Object.defineProperty(obj, 'key', descriptor);
// 2. Being explicit by using a throw-away object literal with all attributes present
Object.defineProperty(obj, 'key2', {
enumerable: false,
configurable: false,
writable: false,
value: 'static'
});
// 3. Recycling same object
function withValue(value) {
const d = withValue.d || (
withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value,
}
);
// avoiding duplicate operation for assigning value
if (d.value !== value) d.value = value;
return d;
}
// and
Object.defineProperty(obj, 'key', withValue('static'));
// if freeze is available, prevents adding or
// removing the object prototype properties
// (value, get, set, enumerable, writable, configurable)
(Object.freeze || Object)(Object.prototype);
```
When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration.
If the old descriptor had its `configurable` attribute set to `false`, the property is said to be *non-configurable*. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../typeerror) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property.
When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped.
Examples
--------
### Creating a property
When the property specified doesn't exist in the object, `Object.defineProperty()` creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are inputted.
```
const o = {}; // Creates a new object
// Example of an object property added
// with defineProperty with a data property descriptor
Object.defineProperty(o, 'a', {
value: 37,
writable: true,
enumerable: true,
configurable: true
});
// 'a' property exists in the o object and its value is 37
// Example of an object property added
// with defineProperty with an accessor property descriptor
let bValue = 38;
Object.defineProperty(o, 'b', {
get() { return bValue; },
set(newValue) { bValue = newValue; },
enumerable: true,
configurable: true
});
o.b; // 38
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue,
// unless o.b is redefined
// You cannot try to mix both:
Object.defineProperty(o, 'conflict', {
value: 0x9f91102,
get() { return 0xdeadbeef; }
});
// throws a TypeError: value appears
// only in data descriptors,
// get appears only in accessor descriptors
```
### Modifying a property
When modifying an existing property, the current property configuration determines if the operator succeeds, does nothing, or throws a [`TypeError`](../typeerror).
#### Writable attribute
When the `writable` property attribute is set to `false`, the property is said to be "non-writable". It cannot be reassigned.
```
const o = {}; // Creates a new object
Object.defineProperty(o, 'a', {
value: 37,
writable: false
});
console.log(o.a); // 37
o.a = 25; // No error thrown
// (it would throw in strict mode,
// even if the value had been the same)
console.log(o.a); // 37; the assignment didn't work
// strict mode
(() => {
'use strict';
const o = {};
Object.defineProperty(o, 'b', {
value: 2,
writable: false,
});
o.b = 3; // throws TypeError: "b" is read-only
return o.b; // returns 2 without the line above
})();
```
As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.
#### Enumerable attribute
The `enumerable` property attribute defines whether the property is picked by [`Object.assign()`](assign) or [spread](../../operators/spread_syntax) operator. For non-[`Symbol`](../symbol) properties it also defines whether it shows up in a [`for...in`](../../statements/for...in) loop and [`Object.keys()`](keys) or not.
```
const o = {};
Object.defineProperty(o, 'a', {
value: 1,
enumerable: true
});
Object.defineProperty(o, 'b', {
value: 2,
enumerable: false
});
Object.defineProperty(o, 'c', {
value: 3
}); // enumerable defaults to false
o.d = 4; // enumerable defaults to true
// when creating a property by setting it
Object.defineProperty(o, Symbol.for('e'), {
value: 5,
enumerable: true
});
Object.defineProperty(o, Symbol.for('f'), {
value: 6,
enumerable: false
});
for (const i in o) {
console.log(i);
}
// Logs 'a' and 'd' (always in that order)
Object.keys(o); // ['a', 'd']
o.propertyIsEnumerable('a'); // true
o.propertyIsEnumerable('b'); // false
o.propertyIsEnumerable('c'); // false
o.propertyIsEnumerable('d'); // true
o.propertyIsEnumerable(Symbol.for('e')); // true
o.propertyIsEnumerable(Symbol.for('f')); // false
const p = { ...o }
p.a // 1
p.b // undefined
p.c // undefined
p.d // 4
p[Symbol.for('e')] // 5
p[Symbol.for('f')] // undefined
```
#### Configurable attribute
The `configurable` attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than `value` and `writable`) can be changed.
When it is `false`, but `writable` is `true`, `value` can still be changed, and `writable` can still be toggled from `true` to `false`; when it is `true`, but `writable` is `false`, `value` may still be replaced with `defineProperty` (but not with assignment operators), and `writable` may be toggled.
```
const o = {};
Object.defineProperty(o, 'a', {
get() { return 1; },
configurable: false,
});
Object.defineProperty(o, 'a', {
configurable: true
}); // throws a TypeError
Object.defineProperty(o, 'a', {
enumerable: true
}); // throws a TypeError
Object.defineProperty(o, 'a', {
set() {}
}); // throws a TypeError (set was undefined previously)
Object.defineProperty(o, 'a', {
get() { return 1; }
}); // throws a TypeError
// (even though the new get does exactly the same thing)
Object.defineProperty(o, 'a', {
value: 12
}); // throws a TypeError // ('value' can be changed when 'configurable' is false but not in this case due to 'get' accessor)
console.log(o.a); // 1
delete o.a; // Nothing happens
console.log(o.a); // 1
Object.defineProperty(o, 'b', {
writable: true,
configurable: false,
});
console.log(o.b); // undefined
Object.defineProperty(o, 'b', {
value: 1,
}); // Even when configurable is false, because the object is writable, we may still replace the value
console.log(o.b); // 1
Object.defineProperty(o, 'b', {
writable: false,
});
Object.defineProperty(o, 'b', {
value: 1,
}); // TypeError: because the property is neither writable nor configurable, it cannot be modified
```
If the `configurable` attribute of `o.a` had been `true`, none of the errors would be thrown and the property would be deleted at the end.
### Adding properties and default values
It is important to consider the way default values of attributes are applied. There is often a difference between using dot notation to assign a value and using `Object.defineProperty()`, as shown in the example below.
```
const o = {};
o.a = 1;
// is equivalent to:
Object.defineProperty(o, 'a', {
value: 1,
writable: true,
configurable: true,
enumerable: true
});
// On the other hand,
Object.defineProperty(o, 'a', { value: 1 });
// is equivalent to:
Object.defineProperty(o, 'a', {
value: 1,
writable: false,
configurable: false,
enumerable: false
});
```
### Custom Setters and Getters
The example below shows how to implement a self-archiving object. When `temperature` property is set, the `archive` array gets a log entry.
```
function Archiver() {
let temperature = null;
const archive = [];
Object.defineProperty(this, 'temperature', {
get() {
console.log('get!');
return temperature;
},
set(value) {
temperature = value;
archive.push({ val: temperature });
}
});
this.getArchive = () => archive;
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
```
In this example, a getter always returns the same value.
```
const pattern = {
get() {
return 'I always return this string, whatever you have assigned';
},
set() {
this.myname = 'this is my name string';
},
};
function TestDefineSetAndGet() {
Object.defineProperty(this, 'myproperty', pattern);
}
const instance = new TestDefineSetAndGet();
instance.myproperty = 'test';
console.log(instance.myproperty);
// I always return this string, whatever you have assigned
console.log(instance.myname); // this is my name string
```
### Inheritance of properties
If an accessor property is inherited, its `get` and `set` methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.
```
function MyClass() {
}
let value;
Object.defineProperty(MyClass.prototype, "x", {
get() {
return value;
},
set(x) {
value = x;
}
});
const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // 1
```
This can be fixed by storing the value in another property. In `get` and `set` methods, `this` points to the object which is used to access or modify the property.
```
function MyClass() {
}
Object.defineProperty(MyClass.prototype, "x", {
get() {
return this.storedX;
},
set(x) {
this.storedX = x;
}
});
const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // undefined
```
Unlike accessor properties, value properties are always set on the object itself, not on a prototype. However, if a non-writable value property is inherited, it still prevents from modifying the property on the object.
```
function MyClass() {
}
MyClass.prototype.x = 1;
Object.defineProperty(MyClass.prototype, "y", {
writable: false,
value: 1
});
const a = new MyClass();
a.x = 2;
console.log(a.x); // 2
console.log(MyClass.prototype.x); // 1
a.y = 2; // Ignored, throws in strict mode
console.log(a.y); // 1
console.log(MyClass.prototype.y); // 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.defineproperty](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.defineproperty) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 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 |
See also
--------
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.defineProperties()`](defineproperties)
* [`Object.prototype.propertyIsEnumerable()`](propertyisenumerable)
* [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor)
* [`get`](../../functions/get)
* [`set`](../../functions/set)
* [`Object.create()`](create)
* [`Reflect.defineProperty()`](../reflect/defineproperty)
| programming_docs |
javascript Object.prototype.__lookupSetter__() Object.prototype.\_\_lookupSetter\_\_()
=======================================
**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:** This feature is deprecated in favor of the [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The `__lookupSetter__()` method returns the function bound as a setter to the specified property.
Syntax
------
```
\_\_lookupSetter\_\_(prop)
```
### Parameters
`prop` A string containing the name of the property whose setter should be returned.
### Return value
The function bound as a setter to the specified property. Returns `undefined` if no such property is found, or the property is a [data property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#data_property).
Description
-----------
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](../object#null-prototype_objects)) inherit the `__lookupSetter__()` method. If a [setter](../../functions/get) has been defined for an object's property, it's not possible to reference the setter function through that property, because that property only calls the function when it's being set. `__lookupSetter__()` can be used to obtain a reference to the setter function.
`__lookupSetter__()` walks up the [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) to find the specified property. If any object along the prototype chain has the specified [own property](hasown), the `set` attribute of the [property descriptor](getownpropertydescriptor) for that property is returned. If that property is a data property, `undefined` is returned. If the property is not found along the entire prototype chain, `undefined` is also returned.
`__lookupSetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__lookupSetter__()`, it also needs to implement the [`__lookupGetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), [`__defineGetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__), and [`__defineSetter__()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__) methods.
Examples
--------
### Using \_\_lookupSetter\_\_()
```
const obj = {
set foo(value) {
this.bar = value;
},
};
obj.\_\_lookupSetter\_\_("foo");
// [Function: set foo]
```
### Looking up a property's setter in the standard way
You should use the [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) API to look up a property's setter. Compared to `__lookupSetter__()`, this method allows looking up [symbol](../symbol) properties. The `Object.getOwnPropertyDescriptor()` method also works with [`null`-prototype objects](../object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__lookupSetter__()` method. If `__lookupSetter__()`'s behavior of walking up the prototype chain is important, you may implement it yourself with [`Object.getPrototypeOf()`](getprototypeof).
```
const obj = {
set foo(value) {
this.bar = value;
},
};
Object.getOwnPropertyDescriptor(obj, "foo").set;
// [Function: set foo]
```
```
const obj2 = {
\_\_proto\_\_: {
set foo(value) {
this.bar = value;
},
},
};
function findSetter(obj, prop) {
while (obj) {
const desc = Object.getOwnPropertyDescriptor(obj, "foo");
if (desc) {
return desc.set;
}
obj = Object.getPrototypeOf(obj);
}
}
console.log(findSetter(obj2, "foo")); // [Function: set foo]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.prototype.\_\_lookupSetter\_\_](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-object.prototype.__lookupSetter__) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `__lookupSetter__` | 1 | 12 | 1 | 11 | 9.5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.prototype.__lookupSetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [`Object.prototype.__lookupGetter__()`](__lookupgetter__)
* [`set`](../../functions/set) syntax
* [`Object.getOwnPropertyDescriptor()`](getownpropertydescriptor) and [`Object.getPrototypeOf()`](getprototypeof)
* [`Object.prototype.__defineGetter__()`](__definegetter__)
* [`Object.prototype.__defineSetter__()`](__definesetter__)
* [JS Guide: Defining Getters and Setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#defining_getters_and_setters)
javascript Object.is() Object.is()
===========
The `Object.is()` static method determines whether two values are [the same value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is).
Syntax
------
```
Object.is(value1, value2)
```
### Parameters
`value1` The first value to compare.
`value2` The second value to compare.
### Return value
A boolean indicating whether or not the two arguments are the same value.
Description
-----------
`Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds:
* both [`undefined`](../undefined)
* both [`null`](../../operators/null)
* both `true` or both `false`
* both strings of the same length with the same characters in the same order
* both the same object (meaning both values reference the same object in memory)
* both [BigInts](../bigint) with the same numeric value
* both [symbols](../symbol) that reference the same symbol value
* both numbers and
+ both `+0`
+ both `-0`
+ both [`NaN`](../nan)
+ or both non-zero, not [`NaN`](../nan), and have the same value
`Object.is()` is not equivalent to the [`==`](../../operators/equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value.
`Object.is()` is also *not* equivalent to the [`===`](../../operators/strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../nan) as not equal to each other.
Examples
--------
### Using Object.is()
```
// Case 1: Evaluation result is the same as using ===
Object.is(25, 25); // true
Object.is("foo", "foo"); // true
Object.is("foo", "bar"); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
const foo = { a: 1 };
const bar = { a: 1 };
const sameFoo = foo;
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(foo, sameFoo); // true
// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true
// Case 3: NaN
Object.is(NaN, 0 / 0); // true
Object.is(NaN, Number.NaN); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.is](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.is) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `is` | 19 | 12 | 22 | No | 15 | 9 | 4.4 | 25 | 22 | 14 | 9 | 1.5 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.is` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) β a comparison of all three built-in sameness facilities
javascript Object.getOwnPropertyNames() Object.getOwnPropertyNames()
============================
The `Object.getOwnPropertyNames()` static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
Try it
------
Syntax
------
```
Object.getOwnPropertyNames(obj)
```
### Parameters
`obj` The object whose enumerable and non-enumerable properties are to be returned.
### Return value
An array of strings that corresponds to the properties found directly in the given object.
Description
-----------
`Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a [`for...in`](../../statements/for...in) loop (or by [`Object.keys()`](keys)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion.
In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, a non-object argument will be coerced to an object.
```
Object.getOwnPropertyNames('foo');
// TypeError: "foo" is not an object (ES5 code)
Object.getOwnPropertyNames('foo');
// ["0", "1", "2", "length"] (ES2015 code)
```
Examples
--------
### Using Object.getOwnPropertyNames()
```
const arr = ['a', 'b', 'c'];
console.log(Object.getOwnPropertyNames(arr).sort());
// ["0", "1", "2", "length"]
// Array-like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).sort());
// ["0", "1", "2"]
Object.getOwnPropertyNames(obj).forEach((val, idx, array) => {
console.log(`${val} -> ${obj[val]}`);
});
// 0 -> a
// 1 -> b
// 2 -> c
// non-enumerable property
const myObj = Object.create({}, {
getFoo: {
value() { return this.foo; },
enumerable: false,
}
});
myObj.foo = 1;
console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"]
```
If you want only the enumerable properties, see [`Object.keys()`](keys) or use a [`for...in`](../../statements/for...in) loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with [`hasOwn()`](hasown)).
Items on the prototype chain are not listed:
```
function ParentClass() {}
ParentClass.prototype.inheritedMethod = function () {};
function ChildClass() {
this.prop = 5;
this.method = function () {};
}
ChildClass.prototype = new ParentClass;
ChildClass.prototype.prototypeMethod = function () {};
console.log(Object.getOwnPropertyNames(new ChildClass()));
// ["prop", "method"]
```
### Get non-enumerable properties only
This uses the [`Array.prototype.filter()`](../array/filter) function to remove the enumerable keys (obtained with [`Object.keys()`](keys)) from a list of all keys (obtained with `Object.getOwnPropertyNames()`) thus giving only the non-enumerable keys as output.
```
const target = myObject;
const enumAndNonenum = Object.getOwnPropertyNames(target);
const enumOnly = new Set(Object.keys(target));
const nonenumOnly = enumAndNonenum.filter((key) => !enumOnly.has(key));
console.log(nonenumOnly);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.getownpropertynames](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.getownpropertynames) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getOwnPropertyNames` | 5 | 12 | 4 | 9 | 12 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Object.getOwnPropertyNames` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.hasOwn()`](hasown)
* [`Object.prototype.propertyIsEnumerable()`](propertyisenumerable)
* [`Object.create()`](create)
* [`Object.keys()`](keys)
* [`Array.prototype.forEach()`](../array/foreach)
javascript Object.isFrozen() Object.isFrozen()
=================
The `Object.isFrozen()` static method determines if an object is [frozen](freeze).
Try it
------
Syntax
------
```
Object.isFrozen(obj)
```
### Parameters
`obj` The object which should be checked.
### Return value
A [`Boolean`](../boolean) indicating whether or not the given object is frozen.
Description
-----------
An object is frozen if and only if it is not [extensible](isextensible), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable.
Examples
--------
### Using Object.isFrozen
```
// A new object is extensible, so it is not frozen.
Object.isFrozen({}); // false
// An empty object which is not extensible
// is vacuously frozen.
const vacuouslyFrozen = Object.preventExtensions({});
Object.isFrozen(vacuouslyFrozen); // true
// A new object with one property is also extensible,
// ergo not frozen.
const oneProp = { p: 42 };
Object.isFrozen(oneProp); // false
// Preventing extensions to the object still doesn't
// make it frozen, because the property is still
// configurable (and writable).
Object.preventExtensions(oneProp);
Object.isFrozen(oneProp); // false
// Deleting that property makes the object vacuously frozen.
delete oneProp.p;
Object.isFrozen(oneProp); // true
// A non-extensible object with a non-writable
// but still configurable property is not frozen.
const nonWritable = { e: 'plep' };
Object.preventExtensions(nonWritable);
Object.defineProperty(nonWritable, 'e', {
writable: false
}); // make non-writable
Object.isFrozen(nonWritable); // false
// Changing that property to non-configurable
// then makes the object frozen.
Object.defineProperty(nonWritable, 'e', {
configurable: false
}); // make non-configurable
Object.isFrozen(nonWritable); // true
// A non-extensible object with a non-configurable
// but still writable property also isn't frozen.
const nonConfigurable = { release: 'the kraken!' };
Object.preventExtensions(nonConfigurable);
Object.defineProperty(nonConfigurable, 'release', {
configurable: false
});
Object.isFrozen(nonConfigurable); // false
// Changing that property to non-writable
// then makes the object frozen.
Object.defineProperty(nonConfigurable, 'release', {
writable: false
});
Object.isFrozen(nonConfigurable); // true
// A non-extensible object with a configurable
// accessor property isn't frozen.
const accessor = { get food() { return 'yum'; } };
Object.preventExtensions(accessor);
Object.isFrozen(accessor); // false
// When we make that property non-configurable it becomes frozen.
Object.defineProperty(accessor, 'food', {
configurable: false
});
Object.isFrozen(accessor); // true
// But the easiest way for an object to be frozen
// is if Object.freeze has been called on it.
const frozen = { 1: 81 };
Object.isFrozen(frozen); // false
Object.freeze(frozen);
Object.isFrozen(frozen); // true
// By definition, a frozen object is non-extensible.
Object.isExtensible(frozen); // false
// Also by definition, a frozen object is sealed.
Object.isSealed(frozen); // true
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, it will return `true` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.
```
Object.isFrozen(1);
// TypeError: 1 is not an object (ES5 code)
Object.isFrozen(1);
// true (ES2015 code)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object.isfrozen](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.isfrozen) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isFrozen` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.freeze()`](freeze)
* [`Object.preventExtensions()`](preventextensions)
* [`Object.isExtensible()`](isextensible)
* [`Object.seal()`](seal)
* [`Object.isSealed()`](issealed)
javascript Boolean.prototype.valueOf() Boolean.prototype.valueOf()
===========================
The `valueOf()` method returns the primitive value of a [`Boolean`](../boolean) object.
Try it
------
Syntax
------
```
valueOf()
```
### Return value
The primitive value of the given [`Boolean`](../boolean) object.
Description
-----------
The `valueOf()` method of [`Boolean`](../boolean) returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type.
This method is usually called internally by JavaScript and not explicitly in code.
Examples
--------
### Using `valueOf()`
```
x = new Boolean();
myVar = x.valueOf(); // assigns false to myVar
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-boolean.prototype.valueof](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-boolean.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` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.prototype.valueOf()`](../object/valueof)
javascript Boolean.prototype.toString() Boolean.prototype.toString()
============================
The `toString()` method returns a string representing the specified boolean value.
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the specified boolean value.
Description
-----------
The [`Boolean`](../boolean) object overrides the `toString` method of [`Object`](../object); it does not inherit [`Object.prototype.toString()`](../object/tostring). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`.
The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../typeerror) for other `this` values without attempting to coerce them to boolean values.
Because `Boolean` doesn't have a [`[@@toPrimitive]()`](../symbol/toprimitive) method, JavaScript calls the `toString()` method automatically when a `Boolean` *object* is used in a context expecting a string, such as in a [template literal](../../template_literals). However, boolean *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.
```
Boolean.prototype.toString = () => "Overridden";
console.log(`${true}`); // "true"
console.log(`${new Boolean(true)}`); // "Overridden"
```
Examples
--------
### Using toString()
```
const flag = new Boolean(true);
console.log(flag.toString()); // "true"
console.log(false.toString()); // "false"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-boolean.prototype.tostring](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-boolean.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 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object.prototype.toString()`](../object/tostring)
| programming_docs |
javascript Boolean() constructor Boolean() constructor
=====================
The `Boolean()` constructor can create [`Boolean`](../boolean) objects or return primitive values of type boolean.
Try it
------
Syntax
------
```
new Boolean(value)
Boolean(value)
```
**Note:** `Boolean()` can be called with or without [`new`](../../operators/new), but with different effects. See [Return value](#return_value).
### Parameters
`value` The initial value of the `Boolean` object.
### Return value
When `Boolean()` is called as a constructor (with [`new`](../../operators/new)), it creates a [`Boolean`](../boolean) object, which is **not** a primitive.
When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive.
**Warning:** You should rarely find yourself using `Boolean` as a constructor.
Description
-----------
The value passed as the first parameter is [converted to a boolean value](../boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](../../operators/null), `false`, [`NaN`](../nan), [`undefined`](../undefined), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`.
**Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/en-US/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used.
Examples
--------
### Creating Boolean objects with an initial value of false
```
const bZero = new Boolean(0);
const bNull = new Boolean(null);
const bEmptyString = new Boolean('');
const bfalse = new Boolean(false);
typeof bfalse // "object"
Boolean(bfalse) // true
```
Note how converting a `Boolean` object to a primitive with `Boolean()` always yields `true`, even if the object holds a value of `false`. You are therefore always advised to avoid constructing `Boolean` wrapper objects.
If you need to take the primitive value out from the wrapper object, instead of using the `Boolean()` function, use the object's [`valueOf()`](valueof) method instead.
```
const bfalse = new Boolean(false);
bfalse.valueOf() // 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-constructor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-boolean-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 |
| `Boolean` | 1 | 12 | 1 | 3 | 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)
javascript ArrayBuffer.prototype.byteLength ArrayBuffer.prototype.byteLength
================================
The `byteLength` accessor property represents the length of an [`ArrayBuffer`](../arraybuffer) in bytes.
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 the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached.
Examples
--------
### Using byteLength
```
const buffer = new ArrayBuffer(8);
buffer.byteLength; // 8
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-arraybuffer.prototype.bytelength](https://tc39.es/ecma262/multipage/structured-data.html#sec-get-arraybuffer.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
--------
* [`ArrayBuffer`](../arraybuffer)
javascript ArrayBuffer() constructor ArrayBuffer() constructor
=========================
The `ArrayBuffer()` constructor is used to create [`ArrayBuffer`](../arraybuffer) objects.
Try it
------
Syntax
------
```
new ArrayBuffer(length)
```
**Note:** `ArrayBuffer()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`length` The size, in bytes, of the array buffer to create.
### Return value
A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0.
### Exceptions
[`RangeError`](../rangeerror) Thrown if the `length` is larger than [`Number.MAX_SAFE_INTEGER`](../number/max_safe_integer) (β₯ 253) or negative.
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-constructor](https://tc39.es/ecma262/multipage/structured-data.html#sec-arraybuffer-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 |
| `ArrayBuffer` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 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 |
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)
javascript ArrayBuffer.isView() ArrayBuffer.isView()
====================
The `ArrayBuffer.isView()` static method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](../typedarray) or a [`DataView`](../dataview).
Try it
------
Syntax
------
```
ArrayBuffer.isView(value)
```
### Parameters
`value` The value to be checked.
### Return value
`true` if the given argument is one of the [`ArrayBuffer`](../arraybuffer) views; otherwise, `false`.
Examples
--------
### Using isView
```
ArrayBuffer.isView(); // false
ArrayBuffer.isView([]); // false
ArrayBuffer.isView({}); // false
ArrayBuffer.isView(null); // false
ArrayBuffer.isView(undefined); // false
ArrayBuffer.isView(new ArrayBuffer(10)); // false
ArrayBuffer.isView(new Uint8Array()); // true
ArrayBuffer.isView(new Float32Array()); // true
ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true
const buffer = new ArrayBuffer(2);
const dv = new DataView(buffer);
ArrayBuffer.isView(dv); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-arraybuffer.isview](https://tc39.es/ecma262/multipage/structured-data.html#sec-arraybuffer.isview) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isView` | 32 | 12 | 29 | 11 | 19 | 7 | 4.4.3 | 32 | 29 | 19 | 7 | 2.0 | 1.0 | 4.0.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
javascript ArrayBuffer.prototype.slice() ArrayBuffer.prototype.slice()
=============================
The `slice()` method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive.
Try it
------
Syntax
------
```
slice(begin)
slice(begin, end)
```
### Parameters
`begin` Zero-based byte index at which to begin slicing.
`end` Optional
Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte.
### Return value
A new [`ArrayBuffer`](../arraybuffer) object.
Description
-----------
The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning.
The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero.
Examples
--------
### Copying an ArrayBuffer
```
const buf1 = new ArrayBuffer(8);
const buf2 = buf1.slice(0);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-arraybuffer.prototype.slice](https://tc39.es/ecma262/multipage/structured-data.html#sec-arraybuffer.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` | 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
--------
* [`ArrayBuffer`](../arraybuffer)
javascript get ArrayBuffer[@@species] get ArrayBuffer[@@species]
==========================
The `ArrayBuffer[@@species]` accessor property returns the constructor used to construct return values from array buffer methods.
**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible.
Syntax
------
```
ArrayBuffer[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 buffer methods that create new array buffers.
Description
-----------
The `@@species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:
```
// Hypothetical underlying implementation for illustration
class ArrayBuffer {
static get [Symbol.species]() {
return this;
}
}
```
Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.
```
class SubArrayBuffer extends ArrayBuffer {}
SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true
```
When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](slice)), the object's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method.
Examples
--------
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is the `ArrayBuffer` constructor for `ArrayBuffer`.
```
ArrayBuffer[Symbol.species]; // function ArrayBuffer()
```
### Species in derived objects
In an instance of a custom `ArrayBuffer` subclass, such as `MyArrayBuffer`, the `MyArrayBuffer` species is the `MyArrayBuffer` constructor. However, you might want to overwrite this, in order to return parent `ArrayBuffer` objects in your derived class methods:
```
class MyArrayBuffer extends ArrayBuffer {
// Overwrite MyArrayBuffer species to the parent ArrayBuffer constructor
static get [Symbol.species]() {
return ArrayBuffer;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-arraybuffer-@@species](https://tc39.es/ecma262/multipage/structured-data.html#sec-get-arraybuffer-@@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
--------
* [`ArrayBuffer`](../arraybuffer)
* [`Symbol.species`](../symbol/species)
javascript Promise.all() Promise.all()
=============
The `Promise.all()` static method takes an iterable of promises as input and returns a single [`Promise`](../promise). This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason.
Try it
------
Syntax
------
```
Promise.all(iterable)
```
### Parameters
`iterable` An [iterable](../../iteration_protocols#the_iterable_protocol) (such as an [`Array`](../array)) of promises.
### Return value
A [`Promise`](../promise) that is:
* **Already fulfilled**, if the `iterable` passed is empty.
* **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled.
* **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected.
Description
-----------
The `Promise.all()` method is one of the [promise concurrency](../promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully β all of whom we want to fulfill before the code execution continues.
`Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](allsettled) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable.
Examples
--------
### Using Promise.all()
`Promise.all` waits for all fulfillments (or the first rejection).
```
const p1 = Promise.resolve(3);
const p2 = 1337;
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("foo");
}, 100);
});
Promise.all([p1, p2, p3]).then((values) => {
console.log(values); // [3, 1337, "foo"]
});
```
If the `iterable` contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):
```
// All values are non-promises, so the returned promise gets fulfilled
const p = Promise.all([1, 2, 3]);
// The only input promise is already fulfilled,
// so the returned promise gets fulfilled
const p2 = Promise.all([1, 2, 3, Promise.resolve(444)]);
// One (and the only) input promise is rejected,
// so the returned promise gets rejected
const p3 = Promise.all([1, 2, 3, Promise.reject(555)]);
// Using setTimeout, we can execute code after the queue is empty
setTimeout(() => {
console.log(p);
console.log(p2);
console.log(p3);
});
// Logs:
// Promise { <state>: "fulfilled", <value>: Array[3] }
// Promise { <state>: "fulfilled", <value>: Array[4] }
// Promise { <state>: "rejected", <reason>: 555 }
```
### Asynchronicity or synchronicity of Promise.all
This following example demonstrates the asynchronicity of `Promise.all` when a non-empty `iterable` is passed:
```
// Passing an array of promises that are already resolved,
// to trigger Promise.all as soon as possible
const resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];
const p = Promise.all(resolvedPromisesArray);
// Immediately logging the value of p
console.log(p);
// Using setTimeout, we can execute code after the queue is empty
setTimeout(() => {
console.log("the queue is now empty");
console.log(p);
});
// Logs, in order:
// Promise { <state>: "pending" }
// the queue is now empty
// Promise { <state>: "fulfilled", <value>: Array[2] }
```
The same thing happens if `Promise.all` rejects:
```
const mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];
const p = Promise.all(mixedPromisesArray);
console.log(p);
setTimeout(() => {
console.log("the queue is now empty");
console.log(p);
});
// Logs:
// Promise { <state>: "pending" }
// the queue is now empty
// Promise { <state>: "rejected", <reason>: 44 }
```
`Promise.all` resolves synchronously if and only if the `iterable` passed is empty:
```
const p = Promise.all([]); // Will be immediately resolved
const p2 = Promise.all([1337, "hi"]); // Non-promise values are ignored, but the evaluation is done asynchronously
console.log(p);
console.log(p2);
setTimeout(() => {
console.log("the queue is now empty");
console.log(p2);
});
// Logs:
// Promise { <state>: "fulfilled", <value>: Array[0] }
// Promise { <state>: "pending" }
// the queue is now empty
// Promise { <state>: "fulfilled", <value>: Array[2] }
```
### Using Promise.all() with async functions
Within [async functions](../../statements/async_function), it's very common to "over-await" your code. For example, given the following functions:
```
function promptForDishChoice() {
return new Promise((resolve, reject) => {
const dialog = document.createElement("dialog");
dialog.innerHTML = `
<form method="dialog">
<p>What would you like to eat?</p>
<select>
<option value="pizza">Pizza</option>
<option value="pasta">Pasta</option>
<option value="salad">Salad</option>
</select>
<menu>
<li><button value="cancel">Cancel</button></li>
<li><button type="submit" value="ok">OK</button></li>
</menu>
</form>
`;
dialog.addEventListener("close", () => {
if (dialog.returnValue === "ok") {
resolve(dialog.querySelector("select").value);
} else {
reject(new Error("User cancelled dialog"));
}
});
document.body.appendChild(dialog);
dialog.showModal();
});
}
async function fetchPrices() {
const response = await fetch("/prices");
return await response.json();
}
```
You may write a function like this:
```
async function getPrice() {
const choice = await promptForDishChoice();
const prices = await fetchPrices();
return prices[choice];
}
```
However, note that the execution of `promptForChoice` and `fetchPrices` don't depend on the result of each other. While the user is choosing their dish, it's fine for the prices to be fetched in the background, but in the code above, the [`await`](../../operators/await) operator causes the async function to pause until the choice is made, and then again until the prices are fetched. We can use `Promise.all` to run them concurrently, so that the user doesn't have to wait for the prices to be fetched before the result is given:
```
async function getPrice() {
const [choice, prices] = await Promise.all([
promptForDishChoice(),
fetchPrices(),
]);
return prices[choice];
}
```
`Promise.all` is the best choice of [concurrency method](../promise#promise_concurrency) here, because error handling is intuitive β if any of the promises reject, the result is no longer available, so the whole `await` expression throws.
`Promise.all` accepts an iterable of promises, so if you are using it to parallelize execution of several async functions, you need to call the async functions and use the returned promises. Directly passing the functions to `Promise.all` does not work, since they are not promises.
```
async function getPrice() {
const [choice, prices] = await Promise.all([
promptForDishChoice,
fetchPrices,
]);
// `choice` and `prices` are still the original async functions;
// Promise.all() does nothing to non-promises
}
```
### Promise.all fail-fast behavior
`Promise.all` is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then `Promise.all` will reject immediately.
```
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("one"), 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("two"), 2000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve("three"), 3000);
});
const p4 = new Promise((resolve, reject) => {
setTimeout(() => resolve("four"), 4000);
});
const p5 = new Promise((resolve, reject) => {
reject(new Error("reject"));
});
// Using .catch:
Promise.all([p1, p2, p3, p4, p5])
.then((values) => {
console.log(values);
})
.catch((error) => {
console.error(error.message);
});
// Logs:
// "reject"
```
It is possible to change this behavior by handling possible rejections:
```
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("p1\_delayed\_resolution"), 1000);
});
const p2 = new Promise((resolve, reject) => {
reject(new Error("p2\_immediate\_rejection"));
});
Promise.all([p1.catch((error) => error), p2.catch((error) => error)]).then(
(values) => {
console.log(values[0]); // "p1\_delayed\_resolution"
console.error(values[1]); // "Error: p2\_immediate\_rejection"
}
);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.all](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.all) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `all` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [`Promise`](../promise)
* [`Promise.allSettled()`](allsettled)
* [`Promise.any()`](any)
* [`Promise.race()`](race)
| programming_docs |
javascript Promise.any() Promise.any()
=============
The `Promise.any()` static method takes an iterable of promises as input and returns a single [`Promise`](../promise). This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an [`AggregateError`](../aggregateerror) containing an array of rejection reasons.
Try it
------
Syntax
------
```
Promise.any(iterable)
```
### Parameters
`iterable` An [iterable](../../iteration_protocols#the_iterable_protocol) (such as an [`Array`](../array)) of promises.
### Return value
A [`Promise`](../promise) that is:
* **Already rejected**, if the `iterable` passed is empty.
* **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled.
* **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an [`AggregateError`](../aggregateerror) containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected.
Description
-----------
The `Promise.any()` method is one of the [promise concurrency](../promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one.
Unlike [`Promise.all()`](all), which returns an *array* of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an *empty iterable*, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../array/some) and [`Array.prototype.every()`](../array/every).
Also, unlike [`Promise.race()`](race), which returns the first *settled* value (either fulfillment or rejection), this method returns the first *fulfilled* value. This method ignores all rejected promises up until the first promise that fulfills.
Examples
--------
### Using Promise.any()
`Promise.any()` fulfills with the first promise to fulfill, even if a promise rejects first. This is in contrast to [`Promise.race()`](race), which fulfills or rejects with the first promise to settle.
```
const pErr = new Promise((resolve, reject) => {
reject("Always fails");
});
const pSlow = new Promise((resolve, reject) => {
setTimeout(resolve, 500, "Done eventually");
});
const pFast = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "Done quick");
});
Promise.any([pErr, pSlow, pFast]).then((value) => {
console.log(value);
// pFast fulfills first
});
// Logs:
// Done quick
```
### Rejections with AggregateError
`Promise.any()` rejects with an [`AggregateError`](../aggregateerror) if no promise fulfills.
```
const failure = new Promise((resolve, reject) => {
reject("Always fails");
});
Promise.any([failure]).catch((err) => {
console.log(err);
});
// AggregateError: No Promise in Promise.any was resolved
```
### Displaying the first image loaded
In this example, we have a function that fetches an image and returns a blob. We use `Promise.any()` to fetch a couple of images and display the first one available (i.e. whose promise has resolved).
```
async function fetchAndDecode(url, description) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.blob();
return [data, description];
}
const coffee = fetchAndDecode("coffee.jpg", "Coffee");
const tea = fetchAndDecode("tea.jpg", "Tea");
Promise.any([coffee, tea])
.then(([blob, description]) => {
const objectURL = URL.createObjectURL(blob);
const image = document.createElement("img");
image.src = objectURL;
image.alt = description;
document.body.appendChild(image);
})
.catch((e) => {
console.error(e);
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.any](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.any) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `any` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
See also
--------
* [Polyfill of `Promise.any` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise)
* [`Promise`](../promise)
* [`Promise.all()`](all)
* [`Promise.allSettled()`](allsettled)
* [`Promise.race()`](race)
javascript Promise.prototype.finally() Promise.prototype.finally()
===========================
The `finally()` method of a [`Promise`](../promise) object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent [`Promise`](../promise) object, allowing you to [chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods.
This lets you avoid duplicating code in both the promise's [`then()`](then) and [`catch()`](catch) handlers.
Try it
------
Syntax
------
```
finally(onFinally)
finally(() => {
// Code that will run after promise is settled (fulfilled or rejected)
})
```
### Parameters
`onFinally` A [`Function`](../function) called when the `Promise` is settled. This handler receives no parameters.
### Return value
Returns an equivalent [`Promise`](../promise). If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise.
Description
-----------
The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.
The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](then). However, there are a couple of differences:
* When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it.
* The `onFinally` callback does not receive any argument. This use case is for precisely when you *do not care* about the rejection reason or the fulfillment value, and so there's no need to provide it.
* A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example:
+ Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`.
+ Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`.
**Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`.
Like [`catch()`](catch), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments β which, for [`Promise.prototype.then()`](then), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following:
**Warning:** This is only for demonstration purposes and is not a polyfill.
```
promise.then(
(value) => Promise.resolve(onFinally()).then(() => value),
(reason) =>
Promise.resolve(onFinally()).then(() => {
throw reason;
}),
);
```
Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](resolve) call above β in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[@@species]`](@@species).
Examples
--------
### Using finally()
```
let isLoading = true;
fetch(myRequest)
.then((response) => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then((json) => {
/\* process your JSON further \*/
})
.catch((error) => {
console.error(error); // this line can also throw, e.g. when console = {}
})
.finally(() => {
isLoading = false;
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.prototype.finally](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.prototype.finally) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `finally` | 63 | 18 | 58 | No | 50 | 11.1 | 63 | 63 | 58 | 46 | 11.3 | 8.0 | 1.0 | 10.0.0 |
See also
--------
* [Polyfill of `Promise.prototype.finally` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise)
* [`Promise`](../promise)
* [`Promise.prototype.then()`](then)
* [`Promise.prototype.catch()`](catch)
javascript Promise() constructor Promise() constructor
=====================
The `Promise()` constructor is primarily used to wrap functions that do not already support promises.
Try it
------
Syntax
------
```
new Promise(executor)
```
**Note:** `Promise()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`executor` A [`function`](../function) to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below.
### Return value
When called via `new`, the `Promise` constructor returns a promise object. The promise object will become *resolved* when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](../promise#description) for more explanation.
Description
-----------
Traditionally (before promises), asynchronous tasks were designed as callbacks.
```
readFile("./data.txt", (error, result) => {
// This callback will be called when the task is done, with the
// final `error` or `result`. Any operation dependent on the
// result must be defined within this callback.
});
// Code here is immediately executed after the `readFile` request
// is fired. It does not wait for the callback to be called, hence
// making `readFile` "asynchronous".
```
To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one.
**Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor.
The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be:
```
function executor(resolveFunc, rejectFunc) {
// Typically, some asynchronous operation that accepts a callback,
// like the `readFile` function above
}
```
`resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type.
```
resolveFunc(value); // call on resolved
rejectFunc(reason); // call on rejected
```
The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver_function) promise). The `rejectFunc` has semantics close to the [`throw`](../../statements/throw) statement, so `reason` is typically an [`Error`](../error) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`.
The `executor`'s completion state has limited effect on the promise's state:
* The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever.
* If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called.
**Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending).
Here's a summary of the typical flow:
1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object.
2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`.
3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments.
4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved".
* If `resolveFunc` is called first, the value passed will be [resolved](#resolver_function). The promise may stay pending (in case another [thenable](../promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value).
* If `rejectFunc` is called first, the promise instantly becomes rejected.
* Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite.
* If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved).
* Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable.
5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`then()`](then), [`catch()`](catch), or [`finally()`](finally). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](../promise#chained_promises)).
For example, the callback-based `readFile` API above can be transformed into a promise-based one.
```
const readFilePromise = (path) =>
new Promise((resolve, reject) => {
readFile(path, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
readFilePromise("./data.txt")
.then((result) => console.log(result))
.catch((error) => console.error("Failed to read data"));
```
### Resolver function
The resolver function `resolveFunc` has the following behaviors:
* If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../typeerror).
* If it's called with a non-[thenable](../promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value.
* If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error.
In the last case, it means code like:
```
new Promise((resolve, reject) => {
resolve(thenable);
});
```
Is roughly equivalent to:
```
new Promise((resolve, reject) => {
try {
thenable.then(
(value) => resolve(value),
(reason) => reject(reason),
);
} catch (e) {
reject(e);
}
});
```
Except that in the `resolve(thenable)` case:
1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet.
2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed.
Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value.
Examples
--------
### Turning a callback-based API into a promise-based one
To provide a function with promise functionality, have it return a promise by calling the `resolve` and `reject` functions at the correct times.
```
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
```
### Effect of calling resolveFunc
Calling `resolveFunc` causes the promise to become resolved, so that calling `resolveFunc` or `rejectFunc` again has no effect. However, the promise may be in any of the states: pending, fulfilled, or rejected.
This `pendingResolved` promise is resolved the time it's created, because it has already been "locked in" to match the eventual state of the inner promise, and calling `resolveOuter` or `rejectOuter` or throwing an error later in the executor has no effect on its eventual state. However, the inner promise is still pending until 100ms later, so the outer promise is also pending:
```
const pendingResolved = new Promise((resolveOuter, rejectOuter) => {
resolveOuter(
new Promise((resolveInner) => {
setTimeout(() => {
resolveInner("inner");
}, 100);
}),
);
});
```
This `fulfilledResolved` promise becomes fulfilled the moment it's resolved, because it's resolved with a non-thenable value. However, when it's created, it's unresolved, because neither `resolve` nor `reject` has been called yet. An unresolved promise is necessarily pending:
```
const fulfilledResolved = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("outer");
}, 100);
});
```
Calling `rejectFunc` obviously causes the promise to reject. However, there are also two ways to cause the promise to instantly become rejected even when the `resolveFunc` callback is called.
```
// 1. Resolving with the promise itself
const rejectedResolved1 = new Promise((resolve) => {
// Note: resolve has to be called asynchronously,
// so that the rejectedResolved1 variable is initialized
setTimeout(() => resolve(rejectedResolved1)); // TypeError: Chaining cycle detected for promise #<Promise>
});
// 2. Resolving with an object which throws when accessing the `then` property
const rejectedResolved2 = new Promise((resolve) => {
resolve({
get then() {
throw new Error("Can't get then property");
},
});
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise-constructor](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-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 |
| `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. |
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)
| programming_docs |
javascript Promise.race() Promise.race()
==============
The `Promise.race()` static method takes an iterable of promises as input and returns a single [`Promise`](../promise). This returned promise settles with the eventual state of the first promise that settles.
Try it
------
Syntax
------
```
Promise.race(iterable)
```
### Parameters
`iterable` An [iterable](../../iteration_protocols#the_iterable_protocol) (such as an [`Array`](../array)) of promises.
### Return value
A [`Promise`](../promise) that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled.
Description
-----------
The `Promise.race()` method is one of the [promise concurrency](../promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).
If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable.
Examples
--------
### Using Promise.race()
This example shows how `Promise.race()` can be used to race several timers implemented with [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout). The timer with the shortest time always wins the race and becomes the resulting promise's state.
```
function sleep(time, value, state) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (state === "fulfill") {
return resolve(value);
} else {
return reject(new Error(value));
}
}, time);
});
}
const p1 = sleep(500, "one", "fulfill");
const p2 = sleep(100, "two", "fulfill");
Promise.race([p1, p2]).then((value) => {
console.log(value); // "two"
// Both fulfill, but p2 is faster
});
const p3 = sleep(100, "three", "fulfill");
const p4 = sleep(500, "four", "reject");
Promise.race([p3, p4]).then(
(value) => {
console.log(value); // "three"
// p3 is faster, so it fulfills
},
(error) => {
// Not called
}
);
const p5 = sleep(500, "five", "fulfill");
const p6 = sleep(100, "six", "reject");
Promise.race([p5, p6]).then(
(value) => {
// Not called
},
(error) => {
console.error(error.message); // "six"
// p6 is faster, so it rejects
}
);
```
### Asynchronicity of Promise.race
This following example demonstrates the asynchronicity of `Promise.race`. Unlike other promise concurrency methods, `Promise.race` is always asynchronous: it never settles synchronously, even when the `iterable` is empty.
```
// Passing an array of promises that are already resolved,
// to trigger Promise.race as soon as possible
const resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];
const p = Promise.race(resolvedPromisesArray);
// Immediately logging the value of p
console.log(p);
// Using setTimeout, we can execute code after the stack is empty
setTimeout(() => {
console.log("the stack is now empty");
console.log(p);
});
// Logs, in order:
// Promise { <state>: "pending" }
// the stack is now empty
// Promise { <state>: "fulfilled", <value>: 33 }
```
An empty iterable causes the returned promise to be forever pending:
```
const foreverPendingPromise = Promise.race([]);
console.log(foreverPendingPromise);
setTimeout(() => {
console.log("the stack is now empty");
console.log(foreverPendingPromise);
});
// Logs, in order:
// Promise { <state>: "pending" }
// the stack is now empty
// Promise { <state>: "pending" }
```
If the iterable contains one or more non-promise value and/or an already settled promise, then `Promise.race` will settle to the first of these values found in the array:
```
const foreverPendingPromise = Promise.race([]);
const alreadyFulfilledProm = Promise.resolve(100);
const arr = [foreverPendingPromise, alreadyFulfilledProm, "non-Promise value"];
const arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(100)];
const p = Promise.race(arr);
const p2 = Promise.race(arr2);
console.log(p);
console.log(p2);
setTimeout(() => {
console.log("the stack is now empty");
console.log(p);
console.log(p2);
});
// Logs, in order:
// Promise { <state>: "pending" }
// Promise { <state>: "pending" }
// the stack is now empty
// Promise { <state>: "fulfilled", <value>: 100 }
// Promise { <state>: "fulfilled", <value>: "non-Promise value" }
```
### Using Promise.race() to implement request timeout
You can race a potentially long-lasting request with a timer that rejects, so that when the time limit has elapsed, the resulting promise automatically rejects.
```
const data = Promise.race([
fetch("/api"),
new Promise((resolve, reject) => {
// Reject after 5 seconds
setTimeout(() => reject(new Error("Request timed out")), 5000);
}),
])
.then((res) => res.json())
.catch((err) => displayError(err));
```
If the `data` promise fulfills, it will contain the data fetched from `/api`; otherwise, it will reject if `fetch` remains pending for 5 seconds and loses the race with the `setTimeout` timer.
### Using Promise.race() to detect the status of a promise
Because `Promise.race()` resolves to the first non-pending promise in the iterable, we can check a promise's state, including if it's pending. This example is adapted from [`promise-status-async`](https://github.com/kudla/promise-status-async/blob/master/lib/promiseState.js).
```
function promiseState(promise) {
const pendingState = { status: "pending" };
return Promise.race([promise, pendingState]).then(
(value) =>
value === pendingState ? value : { status: "fulfilled", value },
(reason) => ({ status: "rejected", reason }),
);
}
```
In this function, if `promise` is pending, the second value, `pendingState`, which is a non-promise, becomes the result of the race; otherwise, if `promise` is already settled, we may know its state through the `onFulfilled` and `onRejected` handlers. For example:
```
const p1 = new Promise((res) => setTimeout(() => res(100), 100));
const p2 = new Promise((res) => setTimeout(() => res(200), 200));
const p3 = new Promise((res, rej) => setTimeout(() => rej(300), 100));
async function getStates() {
console.log(await promiseState(p1));
console.log(await promiseState(p2));
console.log(await promiseState(p3));
}
console.log("Immediately after initiation:");
getStates();
setTimeout(() => {
console.log("After waiting for 100ms:");
getStates();
}, 100);
// Logs:
// Immediately after initiation:
// { status: 'pending' }
// { status: 'pending' }
// { status: 'pending' }
// After waiting for 100ms:
// { status: 'fulfilled', value: 100 }
// { status: 'pending' }
// { status: 'rejected', reason: 300 }
```
**Note:** The `promiseState` function still runs asynchronously, because there is no way to synchronously get a promise's value (i.e. without `then()` or `await`), even when it is already settled. However, `promiseState()` always fulfills within one tick and never actually waits for any promise's settlement.
### Comparison with Promise.any()
`Promise.race` takes the first settled [`Promise`](../promise).
```
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, "one");
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 100, "two");
});
Promise.race([promise1, promise2])
.then((value) => {
console.log("succeeded with value:", value);
})
.catch((reason) => {
// Only promise1 is fulfilled, but promise2 is faster
console.error("failed with reason:", reason);
});
// failed with reason: two
```
[`Promise.any`](any) takes the first fulfilled [`Promise`](../promise).
```
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, "one");
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 100, "two");
});
Promise.any([promise1, promise2])
.then((value) => {
// Only promise1 is fulfilled, even though promise2 settled sooner
console.log("succeeded with value:", value);
})
.catch((reason) => {
console.error("failed with reason:", reason);
});
// succeeded with value: one
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.race](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.race) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `race` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [`Promise`](../promise)
* [`Promise.all()`](all)
* [`Promise.allSettled()`](allsettled)
* [`Promise.any()`](any)
javascript Promise.prototype.then() Promise.prototype.then()
========================
The `then()` method of a [`Promise`](../promise) object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent [`Promise`](../promise) object, allowing you to [chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods.
Try it
------
Syntax
------
```
then(onFulfilled)
then(onFulfilled, onRejected)
then(
(value) => { /\* fulfillment handler \*/ },
(reason) => { /\* rejection handler \*/ },
)
```
### Parameters
`onFulfilled` Optional
A [`Function`](../function) asynchronously called if the `Promise` is fulfilled. This function has one parameter, the *fulfillment value*. If it is not a function, it is internally replaced with an *identity* function (`(x) => x`) which simply passes the fulfillment value forward.
`onRejected` Optional
A [`Function`](../function) asynchronously called if the `Promise` is rejected. This function has one parameter, the *rejection reason*. If it is not a function, it is internally replaced with a *thrower* function (`(x) => { throw x; }`) which throws the rejection reason it received.
### Return value
Returns a new [`Promise`](../promise) immediately. This new promise is always pending when returned, regardless of the current promise's status.
One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function:
* returns a value: `p` gets fulfilled with the returned value as its value.
* doesn't return anything: `p` gets fulfilled with `undefined`.
* throws an error: `p` gets rejected with the thrown error as its value.
* returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value.
* returns an already rejected promise: `p` gets rejected with that promise's value as its value.
* returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler.
Description
-----------
The `then()` method schedules callback functions for the eventual completion of a Promise β either fulfillment or rejection. It is the primitive method of promises: the [thenable](../promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`catch()`](catch) and [`finally()`](finally) methods both work by invoking the object's `then()` method.
For more information about the `onRejected` handler, see the [`catch()`](catch) reference.
`then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement.
[Thenable](../promise#thenables) objects that arise along the `then()` chain are always [resolved](promise#resolver_function) β the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](promise) constructor.
`then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`@@species`](@@species) property.
Examples
--------
### Using the then() method
```
const p1 = new Promise((resolve, reject) => {
resolve("Success!");
// or
// reject(new Error("Error!"));
});
p1.then(
(value) => {
console.log(value); // Success!
},
(reason) => {
console.error(reason); // Error!
},
);
```
### Having a non-function as either parameter
```
Promise.resolve(1).then(2).then(console.log); // 1
Promise.reject(1).then(2, 2).then(console.log, console.log); // 1
```
### Chaining
The `then` method returns a new `Promise`, which allows for method chaining.
If the function passed as handler to `then` returns a `Promise`, an equivalent `Promise` will be exposed to the subsequent `then` in the method chain. The below snippet simulates asynchronous code with the `setTimeout` function.
```
Promise.resolve("foo")
// 1. Receive "foo", concatenate "bar" to it, and resolve that to the next then
.then(
(string) =>
new Promise((resolve, reject) => {
setTimeout(() => {
string += "bar";
resolve(string);
}, 1);
}),
)
// 2. receive "foobar", register a callback function to work on that string
// and print it to the console, but not before returning the unworked on
// string to the next then
.then((string) => {
setTimeout(() => {
string += "baz";
console.log(string); // foobarbaz
}, 1);
return string;
})
// 3. print helpful messages about how the code in this section will be run
// before the string is actually processed by the mocked asynchronous code in the
// previous then block.
.then((string) => {
console.log(
"Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising",
);
// Note that `string` will not have the 'baz' bit of it at this point. This
// is because we mocked that to happen asynchronously with a setTimeout function
console.log(string); // foobar
});
// Logs, in order:
// Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising
// foobar
// foobarbaz
```
The value returned from `then()` is resolved in the same way as [`Promise.resolve()`](resolve). This means [thenable objects](../promise#thenables) are supported, and if the return value is not a promise, it's implicitly wrapped in a `Promise` and then resolved.
```
const p2 = new Promise((resolve, reject) => {
resolve(1);
});
p2.then((value) => {
console.log(value); // 1
return value + 1;
}).then((value) => {
console.log(value, " - A synchronous value works"); // 2 - A synchronous value works
});
p2.then((value) => {
console.log(value); // 1
});
```
A `then` call returns a promise that eventually rejects if the function throws an error or returns a rejected Promise.
```
Promise.resolve()
.then(() => {
// Makes .then() return a rejected promise
throw new Error("Oh no!");
})
.then(
() => {
console.log("Not called.");
},
(error) => {
console.error(`onRejected function called: ${error.message}`);
},
);
```
In practice, it is often desirable to [`catch()`](catch) rejected promises rather than `then()`'s two-case syntax, as demonstrated below.
```
Promise.resolve()
.then(() => {
// Makes .then() return a rejected promise
throw new Error("Oh no!");
})
.catch((error) => {
console.error(`onRejected function called: ${error.message}`);
})
.then(() => {
console.log("I am always called even if the prior then's promise rejects");
});
```
In all other cases, the returned promise eventually fulfills. In the following example, the first `then()` returns `42` wrapped in a fulfilled Promise, even though the previous Promise in the chain was rejected.
```
Promise.reject()
.then(
() => 99,
() => 42,
) // onRejected returns 42 which is wrapped in a fulfilled Promise
.then((solution) => console.log(`Resolved with ${solution}`)); // Fulfilled with 42
```
If `onFulfilled` returns a promise, the return value of `then` will be fulfilled/rejected based on the eventual state of that promise.
```
function resolveLater(resolve, reject) {
setTimeout(() => {
resolve(10);
}, 1000);
}
function rejectLater(resolve, reject) {
setTimeout(() => {
reject(new Error("Error"));
}, 1000);
}
const p1 = Promise.resolve("foo");
const p2 = p1.then(() => {
// Return promise here, that will be resolved to 10 after 1 second
return new Promise(resolveLater);
});
p2.then(
(v) => {
console.log("resolved", v); // "resolved", 10
},
(e) => {
// not called
console.error("rejected", e);
},
);
const p3 = p1.then(() => {
// Return promise here, that will be rejected with 'Error' after 1 second
return new Promise(rejectLater);
});
p3.then(
(v) => {
// not called
console.log("resolved", v);
},
(e) => {
console.error("rejected", e); // "rejected", 'Error'
},
);
```
You can use chaining to implement one function with a Promise-based API on top of another such function.
```
function fetchCurrentData() {
// The fetch() API returns a Promise. This function
// exposes a similar API, except the fulfillment
// value of this function's Promise has had more
// work done on it.
return fetch("current-data.json").then((response) => {
if (response.headers.get("content-type") !== "application/json") {
throw new TypeError();
}
const j = response.json();
// maybe do something with j
// fulfillment value given to user of
// fetchCurrentData().then()
return j;
});
}
```
### Asynchronicity of then()
The following is an example to demonstrate the asynchronicity of the `then` method.
```
// Using a resolved promise 'resolvedProm' for example,
// the function call 'resolvedProm.then(...)' returns a new promise immediately,
// but its handler '(value) => {...}' will get called asynchronously as demonstrated by the console.logs.
// the new promise is assigned to 'thenProm',
// and thenProm will be resolved with the value returned by handler
const resolvedProm = Promise.resolve(33);
console.log(resolvedProm);
const thenProm = resolvedProm.then((value) => {
console.log(
`this gets called after the end of the main stack. the value received is: ${value}, the value returned is: ${
value + 1
}`,
);
return value + 1;
});
console.log(thenProm);
// Using setTimeout, we can postpone the execution of a function to the moment the stack is empty
setTimeout(() => {
console.log(thenProm);
});
// Logs, in order:
// Promise {[[PromiseStatus]]: "resolved", [[PromiseResult]]: 33}
// Promise {[[PromiseStatus]]: "pending", [[PromiseResult]]: undefined}
// "this gets called after the end of the main stack. the value received is: 33, the value returned is: 34"
// Promise {[[PromiseStatus]]: "resolved", [[PromiseResult]]: 34}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.prototype.then](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.prototype.then) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `then` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [`Promise`](../promise)
* [`Promise.prototype.catch()`](catch)
| programming_docs |
javascript Promise.prototype.catch() Promise.prototype.catch()
=========================
The `catch()` method of a [`Promise`](../promise) object schedules a function to be called when the promise is rejected. It immediately returns an equivalent [`Promise`](../promise) object, allowing you to [chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](then).
Try it
------
Syntax
------
```
catch(onRejected)
catch((reason) => {
// rejection handler
})
```
### Parameters
`onRejected` A [`Function`](../function) called when the `Promise` is rejected. This function has one parameter: the *rejection reason*.
### Return value
Returns a new [`Promise`](../promise). This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled.
Description
-----------
The `catch` method is used for error handling in promise composition. Since it returns a [`Promise`](../promise), it [can be chained](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`then()`](then).
If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`then()`](then), [`catch()`](catch), or [`finally()`](finally)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/en-US/docs/Web/API/Window/rejectionhandled_event) event is fired.
`catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods.
```
// overriding original Promise.prototype.then/catch just to add some logs
((Promise) => {
const originalThen = Promise.prototype.then;
const originalCatch = Promise.prototype.catch;
Promise.prototype.then = function (...args) {
console.log("Called .then on %o with arguments: %o", this, args);
return originalThen.apply(this, args);
};
Promise.prototype.catch = function (...args) {
console.error("Called .catch on %o with arguments: %o", this, args);
return originalCatch.apply(this, args);
};
})(Promise);
// calling catch on an already resolved promise
Promise.resolve().catch(function XXX() {});
// Logs:
// Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()]
// Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()]
```
This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected.
Because `catch()` just calls `then()`, it supports subclassing.
**Note:** The examples below are throwing instances of [`Error`](../error). As with synchronous [`throw`](../../statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces.
Examples
--------
### Using and chaining the catch() method
```
const p1 = new Promise((resolve, reject) => {
resolve("Success");
});
p1.then((value) => {
console.log(value); // "Success!"
throw new Error("oh, no!");
})
.catch((e) => {
console.error(e.message); // "oh, no!"
})
.then(
() => console.log("after a catch the chain is restored"),
() => console.log("Not fired due to the catch"),
);
// The following behaves the same as above
p1.then((value) => {
console.log(value); // "Success!"
return Promise.reject("oh, no!");
})
.catch((e) => {
console.error(e); // "oh, no!"
})
.then(
() => console.log("after a catch the chain is restored"),
() => console.log("Not fired due to the catch"),
);
```
### Gotchas when throwing errors
Throwing an error will call the `catch()` method most of the time:
```
const p1 = new Promise((resolve, reject) => {
throw new Error("Uh-oh!");
});
p1.catch((e) => {
console.error(e); // "Uh-oh!"
});
```
Errors thrown inside asynchronous functions will act like uncaught errors:
```
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
throw new Error("Uncaught Exception!");
}, 1000);
});
p2.catch((e) => {
console.error(e); // This is never called
});
```
Errors thrown after `resolve` is called will be silenced:
```
const p3 = new Promise((resolve, reject) => {
resolve();
throw new Error("Silenced Exception!");
});
p3.catch((e) => {
console.error(e); // This is never called
});
```
### catch() is not called if the promise is fulfilled
```
// Create a promise which would not call onReject
const p1 = Promise.resolve("calling next");
const p2 = p1.catch((reason) => {
// This is never called
console.error("catch p1!");
console.error(reason);
});
p2.then(
(value) => {
console.log("next promise's onFulfilled");
console.log(value); // calling next
},
(reason) => {
console.log("next promise's onRejected");
console.log(reason);
},
);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.prototype.catch](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.prototype.catch) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `catch` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [`Promise`](../promise)
* [`Promise.prototype.then()`](then)
* [`Promise.prototype.finally()`](finally)
javascript Promise.allSettled() Promise.allSettled()
====================
The `Promise.allSettled()` static method takes an iterable of promises as input and returns a single [`Promise`](../promise). This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.
Try it
------
Syntax
------
```
Promise.allSettled(iterable)
```
### Parameters
`iterable` An [iterable](../../iteration_protocols#the_iterable_protocol) (such as an [`Array`](../array)) of promises.
### Return value
A [`Promise`](../promise) that is:
* **Already fulfilled**, if the `iterable` passed is empty.
* **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: `status` A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise.
`value` Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with.
`reason` Only present if `status` is `"rejected"`. The reason that the promise was rejected with.
If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled.
Description
-----------
The `Promise.allSettled()` method is one of the [promise concurrency](../promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.
In comparison, the Promise returned by [`Promise.all()`](all) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting.
Examples
--------
### Using Promise.allSettled()
```
Promise.allSettled([
Promise.resolve(33),
new Promise((resolve) => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error("an error")),
]).then((values) => console.log(values));
// [
// { status: 'fulfilled', value: 33 },
// { status: 'fulfilled', value: 66 },
// { status: 'fulfilled', value: 99 },
// { status: 'rejected', reason: Error: an error }
// ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.allsettled](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.allsettled) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `allSettled` | 76 | 79 | 71 | No | 63 | 13 | 76 | 76 | 79 | 54 | 13 | 12.0 | 1.0 | 12.9.0 |
See also
--------
* [Polyfill of `Promise.allSettled` 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)
* [Graceful asynchronous programming with promises](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises)
* [`Promise`](../promise)
* [`Promise.all()`](all)
* [`Promise.any()`](any)
* [`Promise.race()`](race)
javascript get Promise[@@species] get Promise[@@species]
======================
The `Promise[@@species]` accessor property returns the constructor used to construct return values from promise methods.
**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible.
Syntax
------
```
Promise[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 promise chaining methods that create new promises.
Description
-----------
The `@@species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:
```
// Hypothetical underlying implementation for illustration
class Promise {
static get [Symbol.species]() {
return this;
}
}
```
Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.
```
class SubPromise extends Promise {}
SubPromise[Symbol.species] === Promise; // true
```
Promise chaining methods β [`then()`](then), [`catch()`](catch), and [`finally()`](finally) β return new promise objects. They get the constructor to construct the new promise through `this.constructor[@@species]`. If `this.constructor` is `undefined`, or if `this.constructor[@@species]` is `undefined` or `null`, the default [`Promise()`](promise) constructor is used. Otherwise, the constructor returned by `this.constructor[@@species]` is used to construct the new promise object.
Examples
--------
### Species in ordinary objects
The `Symbol.species` property returns the default constructor function, which is the `Promise` constructor for `Promise`.
```
Promise[Symbol.species]; // [Function: Promise]
```
### Species in derived objects
In an instance of a custom `Promise` subclass, such as `MyPromise`, the `MyPromise` species is the `MyPromise` constructor. However, you might want to override this, in order to return parent `Promise` objects in your derived class methods.
```
class MyPromise extends Promise {
// Override MyPromise species to the parent Promise constructor
static get [Symbol.species]() {
return Promise;
}
}
```
By default, promise methods would return promises with the type of the subclass.
```
class MyPromise extends Promise {
someValue = 1;
}
console.log(MyPromise.resolve(1).then(() => {}).someValue); // 1
```
By overriding `@@species`, the promise methods will return the base `Promise` type.
```
class MyPromise extends Promise {
someValue = 1;
static get [Symbol.species]() {
return Promise;
}
}
console.log(MyPromise.resolve(1).then(() => {}).someValue); // undefined
```
Specifications
--------------
**No specification found**No specification data found for `javascript.builtins.Promise.@@species`.
[Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs).
Browser compatibility
---------------------
No compatibility data found for `javascript.builtins.Promise.@@species`.
[Check for problems with this page](#on-github) or contribute missing data to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data).
See also
--------
* [`Promise`](../promise)
* [`Symbol.species`](../symbol/species)
javascript Promise.reject() Promise.reject()
================
The `Promise.reject()` static method returns a `Promise` object that is rejected with a given reason.
Try it
------
Syntax
------
```
Promise.reject(reason)
```
### Parameters
`reason` Reason why this `Promise` rejected.
### Return value
A [`Promise`](../promise) that is rejected with the given reason.
Description
-----------
The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../error).
`Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](promise) constructor β accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`.
Unlike [`Promise.resolve()`](resolve), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`.
Examples
--------
### Using the static Promise.reject() method
```
Promise.reject(new Error("fail")).then(
() => {
// not called
},
(error) => {
console.error(error); // Stacktrace
},
);
```
### Rejecting with a promise
Unlike [`Promise.resolve`](resolve), the `Promise.reject` method does not reuse existing `Promise` instances. It always returns a new `Promise` instance that wraps `reason`.
```
const p = Promise.resolve(1);
const rejected = Promise.reject(p);
console.log(rejected === p); // false
rejected.catch((v) => {
console.log(v === p); // true
});
```
### Calling reject() on a non-Promise constructor
`Promise.reject()` is a generic method. It can be called on any constructor that implements the same signature as the `Promise()` constructor. For example, we can call it on a constructor that passes it `console.log` as `reject`:
```
class NotPromise {
constructor(executor) {
// The "resolve" and "reject" functions behave nothing like the
// native promise's, but Promise.reject() calls them in the same way.
executor(
(value) => console.log("Resolved", value),
(reason) => console.log("Rejected", reason),
);
}
}
Promise.reject.call(NotPromise, "foo"); // Logs "Rejected foo"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.reject](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.reject) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `reject` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [`Promise`](../promise)
javascript Promise.resolve() Promise.resolve()
=================
The `Promise.resolve()` static method "resolves" a given value to a [`Promise`](../promise). If the value is a promise, that promise is returned; if the value is a [thenable](../promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer β a promise that fulfills to a non-thenable value.
Try it
------
Syntax
------
```
Promise.resolve(value)
```
### Parameters
`value` Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve.
### Return value
A [`Promise`](../promise) that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states β fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise.
Description
-----------
`Promise.resolve()` *resolves* a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](../promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value.
`Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](promise) constructor β accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters.
`Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`.
The bulk of the resolving logic is actually implemented by the [resolver function](promise#resolver_function) passed by the `Promise()` constructor. In summary:
* If a non-[thenable](../promise#thenables) value is passed, the returned promise is already fulfilled with that value.
* If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable.
Examples
--------
### Using the static Promise.resolve method
```
Promise.resolve("Success").then(
(value) => {
console.log(value); // "Success"
},
(reason) => {
// not called
},
);
```
### Resolving an array
```
const p = Promise.resolve([1, 2, 3]);
p.then((v) => {
console.log(v[0]); // 1
});
```
### Resolving another Promise
`Promise.resolve()` reuses existing `Promise` instances. If it's resolving a native promise, it returns the same promise instance without creating a wrapper.
```
const original = Promise.resolve(33);
const cast = Promise.resolve(original);
cast.then((value) => {
console.log(`value: ${value}`);
});
console.log(`original === cast ? ${original === cast}`);
// Logs, in order:
// original === cast ? true
// value: 33
```
The inverted order of the logs is due to the fact that the `then` handlers are called asynchronously. See the [`then()`](then) reference for more information.
### Resolving thenables and throwing Errors
```
// Resolving a thenable object
const p1 = Promise.resolve({
then(onFulfill, onReject) {
onFulfill("fulfilled!");
},
});
console.log(p1 instanceof Promise); // true, object casted to a Promise
p1.then(
(v) => {
console.log(v); // "fulfilled!"
},
(e) => {
// not called
},
);
// Thenable throws before callback
// Promise rejects
const thenable = {
then(onFulfilled) {
throw new TypeError("Throwing");
onFulfilled("Resolving");
},
};
const p2 = Promise.resolve(thenable);
p2.then(
(v) => {
// not called
},
(e) => {
console.error(e); // TypeError: Throwing
},
);
// Thenable throws after callback
// Promise resolves
const thenable = {
then(onFulfilled) {
onFulfilled("Resolving");
throw new TypeError("Throwing");
},
};
const p3 = Promise.resolve(thenable);
p3.then(
(v) => {
console.log(v); // "Resolving"
},
(e) => {
// not called
},
);
```
Nested thenables will be "deeply flattened" to a single promise.
```
const thenable = {
then(onFulfilled, onRejected) {
onFulfilled({
// The thenable is fulfilled with another thenable
then(onFulfilled, onRejected) {
onFulfilled(42);
},
});
},
};
Promise.resolve(thenable).then((v) => {
console.log(v); // 42
});
```
**Warning:** Do not call `Promise.resolve()` on a thenable that resolves to itself. That leads to infinite recursion, because it attempts to flatten an infinitely-nested promise.
```
const thenable = {
then(onFulfilled, onRejected) {
onFulfilled(thenable);
},
};
Promise.resolve(thenable); // Will lead to infinite recursion.
```
### Calling resolve() on a non-Promise constructor
`Promise.resolve()` is a generic method. It can be called on any constructor that implements the same signature as the `Promise()` constructor. For example, we can call it on a constructor that passes it `console.log` as `resolve`:
```
class NotPromise {
constructor(executor) {
// The "resolve" and "reject" functions behave nothing like the
// native promise's, but Promise.resolve() calls them in the same way.
executor(
(value) => console.log("Resolved", value),
(reason) => console.log("Rejected", reason),
);
}
}
Promise.resolve.call(NotPromise, "foo"); // Logs "Resolved foo"
```
The ability to flatten nested thenables is implemented by the resolver function of the `Promise()` constructor, so if you call it on another constructor, nested thenables may not be flattened, depending on how that constructor implements its resolver.
```
const thenable = {
then(onFulfilled, onRejected) {
onFulfilled({
// The thenable is fulfilled with another thenable
then(onFulfilled, onRejected) {
onFulfilled(42);
},
});
},
};
Promise.resolve.call(NotPromise, thenable); // Logs "Resolved { then: [Function: then] }"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise.resolve](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.resolve) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolve` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [`Promise`](../promise)
| programming_docs |
javascript Uint32Array() constructor Uint32Array() constructor
=========================
The `Uint32Array()` typed array constructor creates 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).
Syntax
------
```
new Uint32Array()
new Uint32Array(length)
new Uint32Array(typedArray)
new Uint32Array(object)
new Uint32Array(buffer)
new Uint32Array(buffer, byteOffset)
new Uint32Array(buffer, byteOffset, length)
```
**Note:** `Uint32Array()` 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 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 # 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 |
| `Uint32Array` | 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 `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 TypeError() constructor TypeError() constructor
=======================
The `TypeError()` constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.
Syntax
------
```
new TypeError()
new TypeError(message)
new TypeError(message, options)
new TypeError(message, fileName)
new TypeError(message, fileName, lineNumber)
TypeError()
TypeError(message)
TypeError(message, options)
TypeError(message, fileName)
TypeError(message, fileName, lineNumber)
```
**Note:** `TypeError()` can be called with or without [`new`](../../operators/new). Both create a new `TypeError` 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 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-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 |
| `TypeError` | 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)
javascript String.prototype.charCodeAt() String.prototype.charCodeAt()
=============================
The `charCodeAt()` method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index.
Try it
------
The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be *the first part of a surrogate pair* for the code point. If you want the entire code point value, use [`codePointAt()`](codepointat).
Syntax
------
```
charCodeAt(index)
```
### Parameters
`index` An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`.
### Return value
A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns [`NaN`](../nan).
Description
-----------
Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](../string#utf-16_characters_unicode_codepoints_and_grapheme_clusters).)
**Note:** `charCodeAt()` will always return a value that is less than `65536`. This is because the higher code points are represented by *a pair* of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character.
Because of this, in order to examine (or reproduce) the full character for individual character values of `65536` or greater, for such characters, it is necessary to retrieve not only `charCodeAt(i)`, but also `charCodeAt(i+1)` (as if manipulating a string with two letters), or to use `codePointAt(i)` instead. See examples 2 and 3 (below).
`charCodeAt()` returns [`NaN`](../nan) if the given index is less than `0`, or if it is equal to or greater than the `length` of the string.
Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set.
Examples
--------
### Using charCodeAt()
The following example returns `65`, the Unicode value for A.
```
"ABC".charCodeAt(0); // returns 65
```
### Fixing charCodeAt() to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is unknown
This version might be used in for loops and the like when it is unknown whether non-BMP characters exist before the specified index position.
```
function fixedCharCodeAt(str, idx) {
// ex. fixedCharCodeAt('\uD800\uDC00', 0); // 65536
// ex. fixedCharCodeAt('\uD800\uDC00', 1); // false
idx = idx || 0;
const code = str.charCodeAt(idx);
let hi, low;
// High surrogate (could change last hex to 0xDB7F
// to treat high private surrogates
// as single characters)
if (0xd800 <= code && code <= 0xdbff) {
hi = code;
low = str.charCodeAt(idx + 1);
if (isNaN(low)) {
throw new Error(
"High surrogate not followed by low surrogate in fixedCharCodeAt()",
);
}
return (hi - 0xd800) \* 0x400 + (low - 0xdc00) + 0x10000;
}
if (0xdc00 <= code && code <= 0xdfff) {
// Low surrogate
// We return false to allow loops to skip
// this iteration since should have already handled
// high surrogate above in the previous iteration
return false;
// hi = str.charCodeAt(idx - 1);
// low = code;
// return ((hi - 0xD800) \* 0x400) +
// (low - 0xDC00) + 0x10000;
}
return code;
}
```
### Fixing charCodeAt() to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is known
```
function knownCharCodeAt(str, idx) {
str += "";
const end = str.length;
const surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
while (surrogatePairs.exec(str) !== null) {
const li = surrogatePairs.lastIndex;
if (li - 2 < idx) {
idx++;
} else {
break;
}
}
if (idx >= end || idx < 0) {
return NaN;
}
const code = str.charCodeAt(idx);
if (0xd800 <= code && code <= 0xdbff) {
const hi = code;
const low = str.charCodeAt(idx + 1);
// Go one further, since one of the "characters"
// is part of a surrogate pair
return (hi - 0xd800) \* 0x400 + (low - 0xdc00) + 0x10000;
}
return code;
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.charcodeat](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.charcodeat) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `charCodeAt` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.fromCharCode()`](fromcharcode)
* [`String.prototype.charAt()`](charat)
* [`String.fromCodePoint()`](fromcodepoint)
* [`String.prototype.codePointAt()`](codepointat)
javascript String.prototype.toUpperCase() String.prototype.toUpperCase()
==============================
The `toUpperCase()` method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).
Try it
------
Syntax
------
```
toUpperCase()
```
### Return value
A new string representing the calling string converted to upper case.
### Exceptions
[`TypeError`](../typeerror) When called on [`null`](../../operators/null) or [`undefined`](../undefined), for example, `String.prototype.toUpperCase.call(undefined)`.
Description
-----------
The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.
Examples
--------
### Basic usage
```
console.log("alphabet".toUpperCase()); // 'ALPHABET'
```
### Conversion of non-string `this` values to strings
This method will convert any non-string value to a string, when you set its `this` to a value that is not a string:
```
const a = String.prototype.toUpperCase.call({
toString() {
return "abcdef";
},
});
const b = String.prototype.toUpperCase.call(true);
// prints out 'ABCDEF TRUE'.
console.log(a, b);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.touppercase](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.touppercase) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toUpperCase` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.toLocaleLowerCase()`](tolocalelowercase)
* [`String.prototype.toLocaleUpperCase()`](tolocaleuppercase)
* [`String.prototype.toLowerCase()`](tolowercase)
javascript String.prototype.bold() String.prototype.bold()
=======================
**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.
The `bold()` method creates a string that embeds a string in a [`<b>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b) element (`<b>str</b>`), which causes a string to be displayed as bold.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
bold()
```
### Return value
A string beginning with a `<b>` start tag, then the text `str`, and then a `</b>` end tag.
Examples
--------
### Using bold()
The following example uses deprecated string methods to change the formatting of a string:
```
const worldString = "Hello, world";
console.log(worldString.blink()); // <blink>Hello, world</blink>
console.log(worldString.bold()); // <b>Hello, world</b>
console.log(worldString.italics()); // <i>Hello, world</i>
console.log(worldString.strike()); // <strike>Hello, world</strike>
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.bold](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.bold) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `bold` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.bold` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.blink()`](blink)
* [`String.prototype.italics()`](italics)
* [`String.prototype.strike()`](strike)
javascript String.prototype.toLocaleUpperCase() String.prototype.toLocaleUpperCase()
====================================
The `toLocaleUpperCase()` method returns the calling string value converted to upper case, according to any locale-specific case mappings.
Try it
------
Syntax
------
```
toLocaleUpperCase()
toLocaleUpperCase(locales)
```
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../intl#locale_identification_and_negotiation).
### Return value
A new string representing the calling string converted to upper case, according to any locale-specific case mappings.
### Exceptions
* A [`RangeError`](../rangeerror) ("invalid language tag: xx\_yy") is thrown if a `locale` argument isn't a valid language tag.
* A [`TypeError`](../typeerror) ("invalid element in locales argument") is thrown if an array element isn't of type string.
Description
-----------
The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`toUpperCase()`](touppercase), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.
Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()`
Examples
--------
### Using toLocaleUpperCase()
```
"alphabet".toLocaleUpperCase(); // 'ALPHABET'
"GesΓ€Γ".toLocaleUpperCase(); // 'GESΓSS'
"i\u0307".toLocaleUpperCase("lt-LT"); // 'I'
const locales = ["lt", "LT", "lt-LT", "lt-u-co-phonebk", "lt-x-lietuva"];
"i\u0307".toLocaleUpperCase(locales); // 'I'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.tolocaleuppercase](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.tolocaleuppercase) |
| [ECMAScript Internationalization API Specification # sup-string.prototype.tolocaleuppercase](https://tc39.es/ecma402/#sup-string.prototype.tolocaleuppercase) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLocaleUpperCase` | 1 | 12 | 1 | 5.5 | 4 | 1.3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `locale` | 58 | 12 | 55 | 6 | 45 | 10 | 58 | 58 | 55 | 42 | 10 | 7.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. |
See also
--------
* [`String.prototype.toLocaleLowerCase()`](tolocalelowercase)
* [`String.prototype.toLowerCase()`](tolowercase)
* [`String.prototype.toUpperCase()`](touppercase)
javascript String.prototype.blink() String.prototype.blink()
========================
**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.
The `blink()` method creates a string that embeds a string in a [`<blink>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blink) element (`<blink>str</blink>`), which causes a string to blink.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `blink()`, the `<blink>` element itself is non-standard and deprecated, and blinking text is frowned upon by several accessibility standards. Avoid using the element in any way.
Syntax
------
```
blink()
```
### Return value
A string beginning with a `<blink>` start tag, then the text `str`, and then a `</blink>` end tag.
Examples
--------
### Using blink()
The following example uses deprecated string methods to change the formatting of a string:
```
const worldString = "Hello, world";
console.log(worldString.blink()); // <blink>Hello, world</blink>
console.log(worldString.bold()); // <b>Hello, world</b>
console.log(worldString.italics()); // <i>Hello, world</i>
console.log(worldString.strike()); // <strike>Hello, world</strike>
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.blink](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.blink) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `blink` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.blink` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.bold()`](bold)
* [`String.prototype.italics()`](italics)
* [`String.prototype.strike()`](strike)
| programming_docs |
javascript String.prototype.lastIndexOf() String.prototype.lastIndexOf()
==============================
The `lastIndexOf()` method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number.
Try it
------
Syntax
------
```
lastIndexOf(searchString)
lastIndexOf(searchString, position)
```
### Parameters
`searchString` Substring to search for, [coerced to a string](../string#string_coercion).
If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` β because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` β because the substring `"undefined"` is not found in the string `"undefine"`.
`position` Optional
The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` β that is, the method looks for the specified substring only at index `0`.
* `'hello world hello'.lastIndexOf('world', 4)` returns `-1` β because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`.
* `'hello world hello'.lastIndexOf('hello', 99)` returns `12` β because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`.
* `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` β because both cause the method to only look for `hello` at index `0`.
### Return value
The index of the last occurrence of `searchString` found, or `-1` if not found.
Description
-----------
Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1.
```
"canal".lastIndexOf("a"); // returns 3
"canal".lastIndexOf("a", 2); // returns 1
"canal".lastIndexOf("a", 0); // returns -1
"canal".lastIndexOf("x"); // returns -1
"canal".lastIndexOf("c", -5); // returns 0
"canal".lastIndexOf("c", 0); // returns 0
"canal".lastIndexOf(""); // returns 5
"canal".lastIndexOf("", 2); // returns 2
```
### Case-sensitivity
The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`:
```
"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1
```
Examples
--------
### Using indexOf() and lastIndexOf()
The following example uses [`indexOf()`](indexof) and `lastIndexOf()` to locate values in the string "`Brave, Brave New World`".
```
const anyString = "Brave, Brave New World";
console.log(anyString.indexOf("Brave")); // 0
console.log(anyString.lastIndexOf("Brave")); // 7
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.lastindexof](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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 | 6 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.charAt()`](charat)
* [`String.prototype.indexOf()`](indexof)
* [`String.prototype.split()`](split)
* [`Array.prototype.indexOf()`](../array/indexof)
* [`Array.prototype.lastIndexOf()`](../array/lastindexof)
javascript String.prototype.link() String.prototype.link()
=======================
**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.
The `link()` method creates a string that embeds a string in an [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element (`<a href="...">str</a>`), to be used as a hypertext link to another URL.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
link(url)
```
### Parameters
`url` Any string that specifies the `href` attribute of the `<a>` element; it should be a valid URL (relative or absolute), with any `&` characters escaped as `&`.
### Return value
A string beginning with an `<a href="url">` start tag (double quotes in `url` are replaced with `"`), then the text `str`, and then an `</a>` end tag.
Examples
--------
### Using link()
The following example displays the word "MDN" as a hypertext link that returns the user to the Mozilla Developer Network.
```
const hotText = "MDN";
const url = "https://developer.mozilla.org/";
console.log(`Click to return to ${hotText.link(url)}`);
// Click to return to <a href="https://developer.mozilla.org/">MDN</a>
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.link](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.link) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `link` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.link` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.anchor()`](anchor)
* [`document.links`](https://developer.mozilla.org/en-US/docs/Web/API/Document/links)
javascript String.prototype.endsWith() String.prototype.endsWith()
===========================
The `endsWith()` method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate.
Try it
------
Syntax
------
```
endsWith(searchString)
endsWith(searchString, endPosition)
```
### Parameters
`searchString` The characters to be searched for at the end of `str`. Cannot be a regex.
`endPosition` Optional
The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`.
### Return value
`true` if the given characters are found at the end of the string, including when `searchString` is an empty string; otherwise, `false`.
### Exceptions
[`TypeError`](../typeerror) If `searchString` [is a regex](../regexp#special_handling_for_regexes).
Description
-----------
This method lets you determine whether or not a string ends with another string. This method is case-sensitive.
Examples
--------
### Using endsWith()
```
const str = "To be, or not to be, that is the question.";
console.log(str.endsWith("question.")); // true
console.log(str.endsWith("to be")); // false
console.log(str.endsWith("to be", 19)); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.endswith](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.endswith) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `endsWith` | 41 | 12 | 17 | No | 28 | 9 | 37 | 36 | 17 | 24 | 9 | 3.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `String.prototype.endsWith` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.startsWith()`](startswith)
* [`String.prototype.includes()`](includes)
* [`String.prototype.indexOf()`](indexof)
* [`String.prototype.lastIndexOf()`](lastindexof)
javascript String.prototype.matchAll() String.prototype.matchAll()
===========================
The `matchAll()` method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences).
Try it
------
Syntax
------
```
matchAll(regexp)
```
### Parameters
`regexp` A regular expression object, or any object that has a [`Symbol.matchAll`](../symbol/matchall) method.
If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a [`RegExp`](../regexp) by using `new RegExp(regexp, 'g')`.
If `regexp` [is a regex](../regexp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../typeerror) is thrown.
### 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()`](../regexp/exec).
### Exceptions
[`TypeError`](../typeerror) Thrown if the `regexp` [is a regex](../regexp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](../regexp/flags) property does not contain `"g"`).
Description
-----------
The implementation of `String.prototype.matchAll` itself is very simple β it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](../regexp/@@matchall).
Examples
--------
### Regexp.prototype.exec() and matchAll()
Without `matchAll()`, it's possible to use calls to [`regexp.exec()`](../regexp/exec) (and regexes with the `g` flag) in a loop to obtain all the matches:
```
const regexp = /foo[a-z]\*/g;
const str = "table football, foosball";
let match;
while ((match = regexp.exec(str)) !== null) {
console.log(
`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`,
);
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.
```
With `matchAll()` available, you can avoid the [`while`](../../statements/while) loop and `exec` with `g`. Instead, you get an iterator to use with the more convenient [`for...of`](../../statements/for...of), [array spreading](../../operators/spread_syntax), or [`Array.from()`](../array/from) constructs:
```
const regexp = /foo[a-z]\*/g;
const str = "table football, foosball";
const matches = str.matchAll(regexp);
for (const match of matches) {
console.log(
`Found ${match[0]} start=${match.index} end=${
match.index + match[0].length
}.`,
);
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.
// matches iterator is exhausted after the for...of iteration
// Call matchAll again to create a new iterator
Array.from(str.matchAll(regexp), (m) => m[0]);
// [ "football", "foosball" ]
```
`matchAll` will throw an exception if the `g` flag is missing.
```
const regexp = /[a-c]/;
const str = "abc";
str.matchAll(regexp);
// TypeError
```
`matchAll` internally makes a clone of the `regexp` β so, unlike [`regexp.exec()`](../regexp/exec), `lastIndex` does not change as the string is scanned.
```
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" ]
```
However, this means that unlike using [`regexp.exec()`](../regexp/exec) in a loop, you can't mutate `lastIndex` to make the regex advance or rewind.
### Better access to capturing groups (than String.prototype.match())
Another compelling reason for `matchAll` is the improved access to capture groups.
Capture groups are ignored when using [`match()`](match) with the global `g` flag:
```
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";
str.match(regexp); // ['test1', 'test2']
```
Using `matchAll`, you can access capture groups easily:
```
const array = [...str.matchAll(regexp)];
array[0];
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
array[1];
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]
```
### Using matchAll() with a non-RegExp implementing @@matchAll
If an object has a `Symbol.matchAll` method, it can be used as a custom matcher. The return value of `Symbol.matchAll` becomes the return value of `matchAll()`.
```
const str = "Hmm, this is interesting.";
str.matchAll({
[Symbol.matchAll](str) {
return [["Yes, it's interesting."]];
},
}); // returns [["Yes, it's interesting."]]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.matchall](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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 | 11.0 | 1.0 | 12.0.0 |
See also
--------
* [Polyfill of `String.prototype.matchAll` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.match()`](match)
* [Using regular expressions in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
* [Capturing groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences)
* [`RegExp`](../regexp)
* [`RegExp.prototype.exec()`](../regexp/exec)
* [`RegExp.prototype.test()`](../regexp/test)
* [`RegExp.prototype[@@matchAll]()`](../regexp/@@matchall)
javascript String.prototype.padEnd() String.prototype.padEnd()
=========================
The `padEnd()` method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string.
Try it
------
Syntax
------
```
padEnd(targetLength)
padEnd(targetLength, padString)
```
### Parameters
`targetLength` The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is.
`padString` Optional
The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`).
### Return value
A [`String`](../string) of the specified `targetLength` with the `padString` applied at the end of the current `str`.
Examples
--------
### Using padEnd
```
"abc".padEnd(10); // "abc "
"abc".padEnd(10, "foo"); // "abcfoofoof"
"abc".padEnd(6, "123456"); // "abc123"
"abc".padEnd(1); // "abc"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.padend](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.padend) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `padEnd` | 57 | 15 | 48 | No | 44 | 10 | 57 | 57 | 48 | 43 | 10 | 7.0 | 1.0 | 8.0.0
7.0.0 |
See also
--------
* [Polyfill of `String.prototype.padEnd` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.padStart()`](padstart)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/string.polyfill.js)
javascript String.prototype.split() String.prototype.split()
========================
The `split()` method takes a pattern and divides a [`String`](../string) into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
Try it
------
Syntax
------
```
split()
split(separator)
split(separator, limit)
```
### Parameters
`separator` Optional
The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../symbol/split) method β the typical example being a [regular expression](../regexp). If undefined, the original target string is returned wrapped in an array.
`limit` Optional
A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all.
* The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached.
* If `limit` is `0`, `[]` is returned.
### Return value
An [`Array`](../array) of strings, split at each point where the `separator` occurs in the given string.
Description
-----------
If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string.
If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string.
**Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`.
**Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by *user-perceived characters* ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402).
If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](../regexp/unicode) flag is set.
```
"ππ".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"ππ".split(/(?:)/u); // [ "π", "π" ]
```
If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../symbol/split) method.
If `separator` is an object with a [`Symbol.split`](../symbol/split) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`.
Any other value will be coerced to a string before being used as separator.
Examples
--------
### Using split()
When the string is empty and no separator is specified, `split()` returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.
```
const emptyString = "";
// string is empty and no separator is specified
console.log(emptyString.split());
// [""]
// string and separator are both empty strings
console.log(emptyString.split(emptyString));
// []
```
The following example defines a function that splits a string into an array of strings using `separator`. After splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.
```
function splitString(stringToSplit, separator) {
const arrayOfStrings = stringToSplit.split(separator);
console.log("The original string is: ", stringToSplit);
console.log("The separator is: ", separator);
console.log(
"The array has ",
arrayOfStrings.length,
" elements: ",
arrayOfStrings.join(" / "),
);
}
const tempestString = "Oh brave new world that has such people in it.";
const monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
const space = " ";
const comma = ",";
splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
```
This example produces the following output:
```
The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.
The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it.
The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
```
### Removing spaces from a string
In the following example, `split()` looks for zero or more spaces, followed by a semicolon, followed by zero or more spacesβand, when found, removes the spaces and the semicolon from the string. `nameList` is the array returned as a result of `split()`.
```
const names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
console.log(names);
const re = /\s\*(?:;|$)\s\*/;
const nameList = names.split(re);
console.log(nameList);
```
This logs two lines; the first line logs the original string, and the second line logs the resulting array.
```
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
```
### Returning a limited number of splits
In the following example, `split()` looks for spaces in a string and returns the first 3 splits that it finds.
```
const myString = "Hello World. How are you doing?";
const splits = myString.split(" ", 3);
console.log(splits); // [ "Hello", "World.", "How" ]
```
### Splitting with a `RegExp` to include parts of the separator in the result
If `separator` is a regular expression that contains capturing parentheses `( )`, matched results are included in the array.
```
const myString = "Hello 1 word. Sentence number 2.";
const splits = myString.split(/(\d)/);
console.log(splits);
// [ "Hello ", "1", " word. Sentence number ", "2", "." ]
```
**Note:** `\d` matches the [character class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) for digits between 0 and 9.
### Using a custom splitter
An object with a `Symbol.split` method can be used as a splitter with custom behavior.
The following example splits a string using an internal state consisting of an incrementing number:
```
const splitByNumber = {
[Symbol.split](str) {
let num = 1;
let pos = 0;
const result = [];
while (pos < str.length) {
const matchPos = str.indexOf(num, pos);
if (matchPos === -1) {
result.push(str.substring(pos));
break;
}
result.push(str.substring(pos, matchPos));
pos = matchPos + String(num).length;
num++;
}
return result;
},
};
const myString = "a1bc2c5d3e4f";
console.log(myString.split(splitByNumber)); // [ "a", "bc", "c5d", "e", "f" ]
```
The following example uses an internal state to enforce certain behavior, and to ensure a "valid" result is produced.
```
const DELIMITER = ";";
// Split the commands, but remove any invalid or unnecessary values.
const splitCommands = {
[Symbol.split](str, lim) {
const results = [];
const state = {
on: false,
brightness: {
current: 2,
min: 1,
max: 3,
},
};
let pos = 0;
let matchPos = str.indexOf(DELIMITER, pos);
while (matchPos !== -1) {
const subString = str.slice(pos, matchPos).trim();
switch (subString) {
case "light on":
// If the `on` state is already true, do nothing.
if (!state.on) {
state.on = true;
results.push(subString);
}
break;
case "light off":
// If the `on` state is already false, do nothing.
if (state.on) {
state.on = false;
results.push(subString);
}
break;
case "brightness up":
// Enforce a brightness maximum.
if (state.brightness.current < state.brightness.max) {
state.brightness.current += 1;
results.push(subString);
}
break;
case "brightness down":
// Enforce a brightness minimum.
if (state.brightness.current > state.brightness.min) {
state.brightness.current -= 1;
results.push(subString);
}
break;
}
if (results.length === lim) {
break;
}
pos = matchPos + DELIMITER.length;
matchPos = str.indexOf(DELIMITER, pos);
}
// If we broke early due to reaching the split `lim`, don't add the remaining commands.
if (results.length < lim) {
results.push(str.slice(pos).trim());
}
return results;
},
};
const commands =
"light on; brightness up; brightness up; brightness up; light on; brightness down; brightness down; light off";
console.log(commands.split(splitCommands, 3)); // ["light on", "brightness up", "brightness down"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.split](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.split` in `core-js` with fixes and implementation of modern behavior like `Symbol.split` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.charAt()`](charat)
* [`String.prototype.indexOf()`](indexof)
* [`String.prototype.lastIndexOf()`](lastindexof)
* [`Array.prototype.join()`](../array/join)
* [Using regular expressions in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
| programming_docs |
javascript String.prototype.at() String.prototype.at()
=====================
The `at()` method takes an integer value and returns a new [`String`](../string) consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character.
Try it
------
Syntax
------
```
at(index)
```
### Parameters
`index` The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string.
### Return value
A [`String`](../string) consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../undefined) if the given index can not be found.
Examples
--------
### Return the last character of a string
The following example provides a function which returns the last character found in a specified string.
```
// A function which returns the last character of a given string
function returnLast(arr) {
return arr.at(-1);
}
let invoiceRef = "myinvoice01";
console.log(returnLast(invoiceRef)); // '1'
invoiceRef = "myinvoice02";
console.log(returnLast(invoiceRef)); // '2'
```
### Comparing methods
Here we compare different ways to select the penultimate (last but one) character of a [`String`](../string). Whilst all below methods are valid, it highlights the succinctness and readability of the `at()` method.
```
const myString = "Every green bus drives fast.";
// Using length property and charAt() method
const lengthWay = myString.charAt(myString.length - 2);
console.log(lengthWay); // 't'
// Using slice() method
const sliceWay = myString.slice(-2, -1);
console.log(sliceWay); // 't'
// Using at() method
const atWay = myString.at(-2);
console.log(atWay); // 't'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.at](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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 `String.prototype.at` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [A polyfill for the at() method](https://github.com/tc39/proposal-relative-indexing-method#polyfill).
* [`String.prototype.indexOf()`](indexof)
* [`String.prototype.lastIndexOf()`](lastindexof)
* [`String.prototype.charCodeAt()`](charcodeat)
* [`String.prototype.codePointAt()`](codepointat)
* [`String.prototype.split()`](split)
javascript String.prototype.toLowerCase() String.prototype.toLowerCase()
==============================
The `toLowerCase()` method returns the calling string value converted to lower case.
Try it
------
Syntax
------
```
toLowerCase()
```
### Return value
A new string representing the calling string converted to lower case.
Description
-----------
The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself.
Examples
--------
### Using `toLowerCase()`
```
console.log("ALPHABET".toLowerCase()); // 'alphabet'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.tolowercase](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.tolowercase) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLowerCase` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.toLocaleLowerCase()`](tolocalelowercase)
* [`String.prototype.toLocaleUpperCase()`](tolocaleuppercase)
* [`String.prototype.toUpperCase()`](touppercase)
javascript String.prototype.repeat() String.prototype.repeat()
=========================
The `repeat()` method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
Try it
------
Syntax
------
```
repeat(count)
```
### Parameters
`count` An integer between `0` and [`+Infinity`](../number/positive_infinity), indicating the number of times to repeat the string.
### Return value
A new string containing the specified number of copies of the given string.
### Exceptions
* [`RangeError`](../../errors/negative_repetition_count): repeat count must be non-negative.
* [`RangeError`](../../errors/resulting_string_too_large): repeat count must be less than infinity and not overflow maximum string size.
Examples
--------
### Using repeat()
```
"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
'abc'.repeat(1 / 0); // RangeError
({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.repeat](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.repeat) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `repeat` | 41 | 12 | 24 | No | 28 | 9 | 41 | 36 | 24 | 28 | 9 | 3.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `String.prototype.repeat` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.concat()`](concat)
javascript String.prototype.toLocaleLowerCase() String.prototype.toLocaleLowerCase()
====================================
The `toLocaleLowerCase()` method returns the calling string value converted to lower case, according to any locale-specific case mappings.
Try it
------
Syntax
------
```
toLocaleLowerCase()
toLocaleLowerCase(locales)
```
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../intl#locale_identification_and_negotiation).
### Return value
A new string representing the calling string converted to lower case, according to any locale-specific case mappings.
### Exceptions
* A [`RangeError`](../rangeerror) ("invalid language tag: xx\_yy") is thrown if a `locale` argument isn't a valid language tag.
* A [`TypeError`](../typeerror) ("invalid element in locales argument") is thrown if an array element isn't of type string.
Description
-----------
The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`toLowerCase()`](tolowercase), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.
Examples
--------
### Using toLocaleLowerCase()
```
"ALPHABET".toLocaleLowerCase(); // 'alphabet'
"\u0130".toLocaleLowerCase("tr") === "i"; // true
"\u0130".toLocaleLowerCase("en-US") === "i"; // false
const locales = ["tr", "TR", "tr-TR", "tr-u-co-search", "tr-x-turkish"];
"\u0130".toLocaleLowerCase(locales) === "i"; // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.tolocalelowercase](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.tolocalelowercase) |
| [ECMAScript Internationalization API Specification # sup-string.prototype.tolocalelowercase](https://tc39.es/ecma402/#sup-string.prototype.tolocalelowercase) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLocaleLowerCase` | 1 | 12 | 1 | 5.5 | 4 | 1.3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `locale` | 58 | 12 | 55 | 6 | 45 | 10 | 58 | 58 | 55 | 43 | 10 | 7.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. |
See also
--------
* [`String.prototype.toLocaleUpperCase()`](tolocaleuppercase)
* [`String.prototype.toLowerCase()`](tolowercase)
* [`String.prototype.toUpperCase()`](touppercase)
javascript String.prototype.valueOf() String.prototype.valueOf()
==========================
The `valueOf()` method returns the primitive value of a [`String`](../string) object.
Try it
------
Syntax
------
```
valueOf()
```
### Return value
A string representing the primitive value of a given [`String`](../string) object.
Description
-----------
The `valueOf()` method of [`String`](../string) returns the primitive value of a [`String`](../string) object as a string data type. This value is equivalent to [`String.prototype.toString()`](tostring).
This method is usually called internally by JavaScript and not explicitly in code.
Examples
--------
### Using `valueOf()`
```
const x = new String("Hello world");
console.log(x.valueOf()); // 'Hello world'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.valueof](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.toString()`](tostring)
* [`Object.prototype.valueOf()`](../object/valueof)
javascript String.prototype.localeCompare() String.prototype.localeCompare()
================================
The `localeCompare()` method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](../intl/collator) support, this method simply calls `Intl.Collator`.
Try it
------
Syntax
------
```
localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, 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.Collator` API](../intl/collator), these parameters correspond exactly to the [`Intl.Collator()`](../intl/collator/collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent β it's only required to be *consistent*.
`compareString` The string against which the `referenceStr` is compared.
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](../intl/collator/collator#locales) parameter of the `Intl.Collator()` constructor.
In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used.
`options` Optional
An object adjusting the output format. Corresponds to the [`options`](../intl/collator/collator#options) parameter of the `Intl.Collator()` constructor.
In implementations without `Intl.Collator` support, this parameter is ignored.
See the [`Intl.Collator()` constructor](../intl/collator/collator) for details on the `locales` and `options` parameters and how to use them.
### Return value
A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent.
In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`.
Description
-----------
Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`.
* Negative when the `referenceStr` occurs before `compareString`
* Positive when the `referenceStr` occurs after `compareString`
* Returns `0` if they are equivalent
**Warning:** Do not rely on exact return values of `-1` or `1`!
Negative and positive integer results vary between browsers (as well as between browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return `-2` or `2`, or even some other negative or positive value.
Performance
-----------
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](../intl/collator) object and use the function provided by its [`compare()`](../intl/collator/compare) method.
Examples
--------
### Using localeCompare()
```
// The letter "a" is before "c" yielding a negative value
"a".localeCompare("c"); // -2 or -1 (or some other negative value)
// Alphabetically the word "check" comes after "against" yielding a positive value
"check".localeCompare("against"); // 2 or 1 (or some other positive value)
// "a" and "a" are equivalent yielding a neutral value of zero
"a".localeCompare("a"); // 0
```
### Sort an array
`localeCompare()` enables case-insensitive sorting for an array.
```
const items = ["rΓ©servΓ©", "Premier", "ClichΓ©", "communiquΓ©", "cafΓ©", "Adieu"];
items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true }));
// ['Adieu', 'cafΓ©', 'ClichΓ©', 'communiquΓ©', 'Premier', 'rΓ©servΓ©']
```
### Check browser support for extended arguments
The `locales` and `options` arguments are not supported in all browsers yet.
To check whether an implementation supports them, use the `"i"` argument (a requirement that illegal language tags are rejected) and look for a [`RangeError`](../rangeerror) exception:
```
function localeCompareSupportsLocales() {
try {
"foo".localeCompare("bar", "i");
} catch (e) {
return e.name === "RangeError";
}
return false;
}
```
### Using locales
The results provided by `localeCompare()` vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
console.log("Γ€".localeCompare("z", "de")); // a negative value: in German, Γ€ sorts before z
console.log("Γ€".localeCompare("z", "sv")); // a positive value: in Swedish, Γ€ sorts after z
```
### Using options
The results provided by `localeCompare()` can be customized using the `options` argument:
```
// in German, Γ€ has a as the base letter
console.log("Γ€".localeCompare("a", "de", { sensitivity: "base" })); // 0
// in Swedish, Γ€ and a are separate base letters
console.log("Γ€".localeCompare("a", "sv", { sensitivity: "base" })); // a positive value
```
### Numeric sorting
```
// by default, "2" > "10"
console.log("2".localeCompare("10")); // 1
// numeric using options:
console.log("2".localeCompare("10", undefined, { numeric: true })); // -1
// numeric using locales tag:
console.log("2".localeCompare("10", "en-u-kn-true")); // -1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.localecompare](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.localecompare) |
| [ECMAScript Internationalization API Specification # sup-String.prototype.localeCompare](https://tc39.es/ecma402/#sup-String.prototype.localeCompare) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `localeCompare` | 1 | 12 | 1 | 5.5 | 7 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `locales` | 24 | 12 | 29 | 11 | 15 | 10 | No | 26 | 56 | No | 10 | 1.5 | 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` | 24 | 12 | 29 | 11 | 15 | 10 | No | 26 | 56 | No | 10 | 1.5 | 1.0 | 0.12.0 |
See also
--------
* [`Intl.Collator`](../intl/collator)
javascript String.fromCodePoint() String.fromCodePoint()
======================
The `String.fromCodePoint()` static method returns a string created by using the specified sequence of code points.
Try it
------
Syntax
------
```
String.fromCodePoint(num1)
String.fromCodePoint(num1, num2)
String.fromCodePoint(num1, num2, /\* β¦, \*/ numN)
```
### Parameters
`num1, ..., numN` A sequence of code points.
### Return value
A string created by using the specified sequence of code points.
### Exceptions
* A [`RangeError`](../../errors/not_a_codepoint) is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`).
Description
-----------
This method returns a string (and *not* a [`String`](../string) object).
Because `fromCodePoint()` is a static method of [`String`](../string), you must call it as `String.fromCodePoint()`, rather than as a method of a [`String`](../string) object you created.
Examples
--------
### Using fromCodePoint()
Valid input:
```
String.fromCodePoint(42); // "\*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404" === "Π"
String.fromCodePoint(0x2f804); // "\uD87E\uDC04"
String.fromCodePoint(194564); // "\uD87E\uDC04"
String.fromCodePoint(0x1d306, 0x61, 0x1d307); // "\uD834\uDF06a\uD834\uDF07"
```
Invalid input:
```
String.fromCodePoint("\_"); // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1); // RangeError
String.fromCodePoint(3.14); // RangeError
String.fromCodePoint(3e-2); // RangeError
String.fromCodePoint(NaN); // RangeError
```
### Compared to fromCharCode()
[`String.fromCharCode()`](fromcharcode) cannot return supplementary characters (i.e. code points `0x010000` β `0x10FFFF`) by specifying their code point. Instead, it requires the UTF-16 surrogate pair in order to return a supplementary character:
```
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"
```
`String.fromCodePoint()`, on the other hand, can return 4-byte supplementary characters, as well as the more common 2-byte BMP characters, by specifying their code point (which is equivalent to the UTF-32 code unit):
```
String.fromCodePoint(0x1f303); // or 127747 in decimal
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.fromcodepoint](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.fromcodepoint) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fromCodePoint` | 41 | 12 | 29 | No | 28 | 9 | 41 | 41 | 29 | 28 | 9 | 4.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `String.fromCodePoint` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.fromCharCode()`](fromcharcode)
* [`String.prototype.charAt()`](charat)
* [`String.prototype.codePointAt()`](codepointat)
* [`String.prototype.charCodeAt()`](charcodeat)
| programming_docs |
javascript String length String length
=============
The `length` data property of a string contains the length of the string in UTF-16 code units.
Try it
------
Value
-----
A non-negative integer.
| Property attributes of `String length` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
This property returns the number of code units in the string. JavaScript uses [UTF-16](../string#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters.
The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](../number/max_safe_integer). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer.
* In V8 (used by Chrome and Node), the maximum length is 229 - 24 (~1GiB). On 32-bit systems, the maximum length is 228 - 16 (~512MiB).
* In Firefox, the maximum length is 230 - 2 (~2GiB). Before Firefox 65, the maximum length was 228 - 1 (~512MiB).
* In Safari, the maximum length is 231 - 1 (~4GiB).
For an empty string, `length` is 0.
The static property `String.length` is unrelated to the length of strings. It's the [arity](../function/length) of the `String` function (loosely, the number of formal parameters it has), which is 1.
Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](@@iterator), which iterates by characters:
```
function getCharacterLength(str) {
// The string iterator that is used here iterates over characters,
// not mere code units
return [...str].length;
}
console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3
```
Examples
--------
### Basic usage
```
const x = "Mozilla";
const empty = "";
console.log(`${x} is ${x.length} code units long`);
// Mozilla is 7 code units long
console.log(`The empty string has a length of ${empty.length}`);
// The empty string has a length of 0
```
### Strings with length not equal to the number of characters
```
const emoji = "π";
console.log(emoji.length); // 2
const adlam = "π€²π₯π€£π€«";
console.log(adlam.length); // 8
const formula = "βπ₯ββ,π₯Β²β₯0";
console.log(formula.length); // 11
```
### Assigning to length
Because string is a primitive, attempting to assign a value to a string's `length` property has no observable effect, and will throw in [strict mode](../../strict_mode).
```
const myString = "bluebells";
myString.length = 4;
console.log(myString); // "bluebells"
console.log(myString.length); // 9
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-properties-of-string-instances-length](https://tc39.es/ecma262/multipage/text-processing.html#sec-properties-of-string-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 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [JavaScript `String.length` and Internationalizing Web Applications](https://downloads.teradata.com/blog/jasonstrimpel/2011/11/javascript-string-length-and-internationalizing-web-applications)
javascript String.prototype.replace() String.prototype.replace()
==========================
The `replace()` method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a [`RegExp`](../regexp), and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged.
Try it
------
Syntax
------
```
replace(pattern, replacement)
```
### Parameters
`pattern` Can be a string or an object with a [`Symbol.replace`](../symbol/replace) method β the typical example being a [regular expression](../regexp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string.
`replacement` Can be a string or a function.
* If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying_a_string_as_the_replacement) section below.
* If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying_a_function_as_the_replacement) section below.
### Return value
A new string, with one, some, or all matches of the pattern replaced by the specified replacement.
Description
-----------
This method does not mutate the string value it's called on. It returns a new string.
A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](replaceall) instead.
If `pattern` is an object with a [`Symbol.replace`](../symbol/replace) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method β for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](../regexp/@@replace).
If the `pattern` is an empty string, the replacement is prepended to the start of the string.
```
"xxx".replace("", "\_"); // "\_xxx"
```
A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](../regexp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](../regexp/@@replace).
### Specifying a string as the replacement
The replacement string can include the following special replacement patterns:
| Pattern | Inserts |
| --- | --- |
| `$$` | Inserts a `"$"`. |
| `$&` | Inserts the matched substring. |
| `$`` | Inserts the portion of the string that precedes the matched substring. |
| `$'` | Inserts the portion of the string that follows the matched substring. |
| `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. |
| `$<Name>` | Inserts the named capturing group where `Name` is the group name. |
`$n` and `$<Name>` are only available if the `pattern` argument is a [`RegExp`](../regexp) object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string.
```
"foo".replace(/(f)/, "$2");
// "$2oo"; the regex doesn't have the second group
"foo".replace("f", "$1");
// "$1oo"; the pattern is a string, so it doesn't have any groups
"foo".replace(/(f)|(g)/, "$2");
// "oo"; the second group exists but isn't matched
```
### Specifying a function as the replacement
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.
**Note:** The above-mentioned special replacement patterns do *not* apply for strings returned from the replacer function.
The function has the following signature:
```
function replacer(match, p1, p2, /\* β¦, \*/ pN, offset, string, groups) {
return replacement;
}
```
The arguments to the function are as follows:
`match` The matched substring. (Corresponds to `$&` above.)
`p1, p2, β¦, pN` The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a [`RegExp`](../regexp) object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`.
`offset` The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`.
`string` The whole string being examined.
`groups` An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group.
The exact number of arguments depends on whether the first argument is a [`RegExp`](../regexp) object β and, if so, how many capture groups it has.
The following example will set `newString` to `'abc - 12345 - #$*%'`:
```
function replacer(match, p1, p2, p3, offset, string) {
// p1 is non-digits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(" - ");
}
const newString = "abc12345#$\*%".replace(/([^\d]\*)(\d\*)([^\w]\*)/, replacer);
console.log(newString); // abc - 12345 - #$\*%
```
The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
Examples
--------
### Defining the regular expression in replace()
In the following example, the regular expression is defined in `replace()` and includes the ignore case flag.
```
const str = "Twas the night before Xmas...";
const newstr = str.replace(/xmas/i, "Christmas");
console.log(newstr); // Twas the night before Christmas...
```
This logs `'Twas the night before Christmas...'`.
**Note:** See [the regular expression guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) for more explanations about regular expressions.
### Using the global and ignoreCase flags with replace()
Global replace can only be done with a regular expression. In the following example, the regular expression includes the [global and ignore case flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags) which permits `replace()` to replace each occurrence of `'apples'` in the string with `'oranges'`.
```
const re = /apples/gi;
const str = "Apples are round, and apples are juicy.";
const newstr = str.replace(re, "oranges");
console.log(newstr); // oranges are round, and oranges are juicy.
```
This logs `'oranges are round, and oranges are juicy'`.
### Switching words in a string
The following script switches the words in the string. For the replacement text, the script uses [capturing groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences) and the `$1` and `$2` replacement patterns.
```
const re = /(\w+)\s(\w+)/;
const str = "Maria Cruz";
const newstr = str.replace(re, "$2, $1");
console.log(newstr); // Cruz, Maria
```
This logs `'Cruz, Maria'`.
### Using an inline function that modifies the matched characters
In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.
The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.
```
function styleHyphenFormat(propertyName) {
function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? "-" : "") + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
```
Given `styleHyphenFormat('borderTop')`, this returns `'border-top'`.
Because we want to further transform the *result* of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the [`toLowerCase()`](tolowercase) method. If we had tried to do this using the match without a function, the [`toLowerCase()`](tolowercase) would have no effect.
```
// Won't work
const newString = propertyName.replace(/[A-Z]/g, "-" + "$&".toLowerCase());
```
This is because `'$&'.toLowerCase()` would first be evaluated as a string literal (resulting in the same `'$&'`) before using the characters as a pattern.
### Replacing a Fahrenheit degree with its Celsius equivalent
The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with `"F"`. The function returns the Celsius number ending with `"C"`. For example, if the input number is `"212F"`, the function returns `"100C"`. If the number is `"0F"`, the function returns `"-17.77777777777778C"`.
The regular expression `test` checks for any number that ends with `F`. The number of Fahrenheit degrees is accessible to the function through its second parameter, `p1`. The function sets the Celsius number based on the number of Fahrenheit degrees passed in a string to the `f2c()` function. `f2c()` then returns the Celsius number. This function approximates Perl's `s///e` flag.
```
function f2c(x) {
function convert(str, p1, offset, s) {
return `${((p1 - 32) \* 5) / 9}C`;
}
const s = String(x);
const test = /(-?\d+(?:\.\d\*)?)F\b/g;
return s.replace(test, convert);
}
```
### Making a generic replacer
Suppose we want to create a replacer that appends the offset data to every matched string. Because the replacer function already receives the `offset` parameter, it will be trivial if the regex is statically known.
```
"abcd".replace(/(bc)/, (match, p1, offset) => `${match} (${offset}) `);
// "abc (1) d"
```
However, this replacer would be hard to generalize if we want it to work with any regex pattern. The replacer is *variadic* β the number of arguments it receives depends on the number of capturing groups present. We can use [rest parameters](../../functions/rest_parameters), but it would also collect `offset`, `string`, etc. into the array. The fact that `groups` may or may not be passed depending on the identity of the regex would also make it hard to generically know which argument corresponds to the `offset`.
```
function addOffset(match, ...args) {
const offset = args.at(-2);
return `${match} (${offset}) `;
}
console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"
console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (abcd) d"
```
The `addOffset` example above doesn't work when the regex contains a named group, because in this case `args.at(-2)` would be the `string` instead of the `offset`.
Instead, you need to extract the last few arguments based on type, because `groups` is an object while `string` is a string.
```
function addOffset(match, ...args) {
const hasNamedGroups = typeof args.at(-1) === "object";
const offset = hasNamedGroups ? args.at(-3) : args.at(-2);
return `${match} (${offset}) `;
}
console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"
console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (1) d"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.replace](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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` | 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 |
See also
--------
* [Polyfill of `String.prototype.replace` in `core-js` with fixes and implementation of modern behavior like `Symbol.replace` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.replaceAll()`](replaceall)
* [`String.prototype.match()`](match)
* [`RegExp.prototype.exec()`](../regexp/exec)
* [`RegExp.prototype.test()`](../regexp/test)
* [`Symbol.replace`](../symbol/replace)
* [`RegExp.prototype[@@replace]()`](../regexp/@@replace)
javascript String.prototype.fontcolor() String.prototype.fontcolor()
============================
**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.
The `fontcolor()` method creates a string that embeds a string in a [`<font>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font) element (`<font color="...">str</font>`), which causes a string to be displayed in the specified font color.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `fontcolor()`, the `<font>` element itself has been removed in [HTML5](https://developer.mozilla.org/en-US/docs/Glossary/HTML5) and shouldn't be used anymore. Web developers should use [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) properties instead.
Syntax
------
```
fontcolor(color)
```
### Parameters
`color` A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals for color names are listed in the [CSS color reference](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
### Return value
A string beginning with a `<font color="color">` start tag (double quotes in `color` are replaced with `"`), then the text `str`, and then a `</font>` end tag.
Description
-----------
The `fontcolor()` method itself simply joins the string parts together without any validation or normalization. However, to create valid [`<font>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font) elements, if you express color as a hexadecimal RGB triplet, you must use the format `rrggbb`. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is `"FA8072"`.
Examples
--------
### Using fontcolor()
The following example uses the `fontcolor()` method to change the color of a string by producing a string with the HTML `<font>` element.
```
const worldString = "Hello, world";
console.log(`${worldString.fontcolor("red")} is red in this line`);
// '<font color="red">Hello, world</font> is red in this line'
console.log(
`${worldString.fontcolor("FF00")} is red in hexadecimal in this line`,
);
// '<font color="FF00">Hello, world</font> is red in hexadecimal in this line'
```
With the [`element.style`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) object you can get the element's `style` attribute and manipulate it more generically, for example:
```
document.getElementById("yourElemId").style.color = "red";
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.fontcolor](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.fontcolor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fontcolor` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.fontcolor` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.fontsize()`](fontsize)
| programming_docs |
javascript String.prototype.trimStart() String.prototype.trimStart()
============================
The `trimStart()` method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method.
Try it
------
Syntax
------
```
trimStart()
trimLeft()
```
### Return value
A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](../../lexical_grammar#white_space) characters plus [line terminators](../../lexical_grammar#line_terminators).
If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`).
### Aliasing
After [`trim()`](trim) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`padEnd()`](padend), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means:
```
String.prototype.trimLeft.name === "trimStart";
```
Examples
--------
### Using trimStart()
The following example trims whitespace from the start of `str`, but not from its end.
```
let str = " foo ";
console.log(str.length); // 8
str = str.trimStart();
console.log(str.length); // 5
console.log(str); // 'foo '
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.trimstart](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.trimstart) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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 |
See also
--------
* [Polyfill of `String.prototype.trimStart` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.trim()`](trim)
* [`String.prototype.trimEnd()`](trimend)
javascript String.prototype.trim() String.prototype.trim()
=======================
The `trim()` method removes whitespace from both ends of a string and returns a new string, without modifying the original string.
To return a new string with whitespace trimmed from just one end, use [`trimStart()`](trimstart) or [`trimEnd()`](trimend).
Try it
------
Syntax
------
```
trim()
```
### Return value
A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](../../lexical_grammar#white_space) characters plus [line terminators](../../lexical_grammar#line_terminators).
If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`).
Examples
--------
### Using trim()
The following example trims whitespace from both ends of `str`.
```
const str = " foo ";
console.log(str.trim()); // 'foo'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.trim](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.trim) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Trim` | 4 | 12 | 3.5 | 10 | 10.5 | 5 | β€37 | 18 | 4 | 11 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.trimStart()`](trimstart)
* [`String.prototype.trimEnd()`](trimend)
javascript String() constructor String() constructor
====================
The `String` constructor is used to create a new [`String`](../string) object. When called instead as a function, it performs type conversion to a [primitive string](https://developer.mozilla.org/en-US/docs/Glossary/String), which is usually more useful.
Syntax
------
```
new String(thing)
String(thing)
```
**Note:** `String()` can be called with or without [`new`](../../operators/new), but with different effects. See [Return value](#return_value).
### Parameters
`thing` Anything to be converted to a string.
### Return value
When `String` is called as a constructor (with `new`), it creates a [`String`](../string) object, which is **not** a primitive.
When `String` is called as a function, it coerces the parameter to a string primitive. [Symbol](../symbol) values would be converted to `"Symbol(description)"`, where `description` is the [description](../symbol/description) of the Symbol, instead of throwing.
**Warning:** You should rarely find yourself using `String` as a constructor.
Examples
--------
### String constructor and String function
String function and String constructor produce different results:
```
const a = new String("Hello world"); // a === "Hello world" is false
const b = String("Hello world"); // b === "Hello world" is true
a instanceof String; // is true
b instanceof String; // is false
typeof a; // "object"
typeof b; // "string"
```
Here, the function produces a string (the [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) type) as promised. However, the constructor produces an instance of the type String (an object wrapper) and that's why you rarely want to use the String constructor at all.
### Using String() to stringify a symbol
`String()` is the only case where a symbol can be converted to a string without throwing, because it's very explicit.
```
const sym = Symbol("example");
`${sym}`; // TypeError: Cannot convert a Symbol value to a string
"" + sym; // TypeError: Cannot convert a Symbol value to a string
"".concat(sym); // TypeError: Cannot convert a Symbol value to a string
```
```
const sym = Symbol("example");
String(sym); // "Symbol(example)"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string-constructor](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-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 |
| `String` | 1 | 12 | 1 | 3 | 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)
javascript String.fromCharCode() String.fromCharCode()
=====================
The `String.fromCharCode()` static method returns a string created from the specified sequence of UTF-16 code units.
Try it
------
Syntax
------
```
String.fromCharCode(num1)
String.fromCharCode(num1, num2)
String.fromCharCode(num1, num2, /\* β¦, \*/ numN)
```
### Parameters
`num1, ..., numN` A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed.
### Return value
A string of length `N` consisting of the `N` specified UTF-16 code units.
Description
-----------
This method returns a string and not a [`String`](../string) object.
Because `fromCharCode()` is a static method of [`String`](../string), you always use it as `String.fromCharCode()`, rather than as a method of a [`String`](../string) object you created.
### Returning supplementary characters
In UTF-16, the most common characters can be represented by a single 16-bit value (i.e. a code unit). However, this set of characters, known as the Base Multilingual Plane (BMP), is only 1/17th of the total addressable Unicode code points. The remaining code points, in the range of `65536` (`0x010000`) to `1114111` (`0x10FFFF`) are known as supplementary characters. In UTF-16, supplementary characters are represented by two 16-bit code units, known as surrogates, that were reserved for this purpose. A valid combination of two surrogates used to represent a supplementary character is known as a surrogate pair.
Because `fromCharCode()` only works with 16-bit values (same as the `\u` escape sequence), a surrogate pair is required in order to return a supplementary character. For example, both `String.fromCharCode(0xD83C, 0xDF03)` and `\uD83C\uDF03` return code point `U+1F303` "Night with Stars".
While there is a mathematical relationship between the supplementary code point value (e.g. `0x1F303`) and both surrogate values that represent it (e.g., `0xD83C` and `0xDF03`), it does require an extra step to either calculate or look up the surrogate pair values every time a supplementary code point is to be used. For this reason, it's more convenient to use [`String.fromCodePoint()`](fromcodepoint), which allows for returning supplementary characters based on their actual code point value. For example, `String.fromCodePoint(0x1F303)` returns code point `U+1F303` "Night with Stars".
Examples
--------
### Using fromCharCode()
BMP characters, in UTF-16, use a single code unit:
```
String.fromCharCode(65, 66, 67); // returns "ABC"
String.fromCharCode(0x2014); // returns "β"
String.fromCharCode(0x12014); // also returns "β"; the digit 1 is truncated and ignored
String.fromCharCode(8212); // also returns "β"; 8212 is the decimal form of 0x2014
```
Supplementary characters, in UTF-16, require two code units (i.e. a surrogate pair):
```
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"
String.fromCharCode(0xd834, 0xdf06, 0x61, 0xd834, 0xdf07); // "\uD834\uDF06a\uD834\uDF07"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.fromcharcode](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.fromcharcode) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fromCharCode` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.fromCodePoint()`](fromcodepoint)
* [`String.prototype.charAt()`](charat)
* [`String.prototype.charCodeAt()`](charcodeat)
* [`String.prototype.codePointAt()`](codepointat)
javascript String.prototype[@@iterator]() String.prototype[@@iterator]()
==============================
The `@@iterator` method of a string implements the [iterable protocol](../../iteration_protocols) and allows strings 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 Unicode code points of the string value as individual strings.
Try it
------
Syntax
------
```
string[Symbol.iterator]()
```
### Return value
A new iterable iterator object that yields the Unicode code points of the string value as individual strings.
Description
-----------
Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved.
```
// "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
```
Examples
--------
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes strings [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 str = "A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A";
for (const v of str) {
console.log(v);
}
// "A"
// "\uD835\uDC68"
// "B"
// "\uD835\uDC69"
// "C"
// "\uD835\uDC6A"
```
### 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 str = "A\uD835\uDC68";
const strIter = str[Symbol.iterator]();
console.log(strIter.next().value); // "A"
console.log(strIter.next().value); // "\uD835\uDC68"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype-@@iterator](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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 | 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 |
See also
--------
* [Polyfill of `String.prototype[@@iterator]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [Iteration protocols](../../iteration_protocols)
javascript String.prototype.sub() String.prototype.sub()
======================
**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.
The `sub()` method creates a string that embeds a string in a [`<sub>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub) element (`<sub>str</sub>`), which causes a string to be displayed as subscript.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
sub()
```
### Return value
A string beginning with a `<sub>` start tag, then the text `str`, and then a `</sub>` end tag.
Examples
--------
### Using sub() and sup() methods
The following example uses the `sub()` and [`sup()`](sup) methods to format a string:
```
const superText = "superscript";
const subText = "subscript";
console.log(`This is what a ${superText.sup()} looks like.`);
// "This is what a <sup>superscript</sup> looks like."
console.log(`This is what a ${subText.sub()} looks like.`);
// "This is what a <sub>subscript</sub> looks like."
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.sub](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.sub) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sub` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.sub` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.sup()`](sup)
javascript String.prototype.slice() String.prototype.slice()
========================
The `slice()` method extracts a section of a string and returns it as a new string, without modifying the original string.
Try it
------
Syntax
------
```
slice(indexStart)
slice(indexStart, indexEnd)
```
### Parameters
`indexStart` The index of the first character to include in the returned substring.
`indexEnd` Optional
The index of the first character to exclude from the returned substring.
### Return value
A new string containing the extracted section of the string.
Description
-----------
`slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.
`slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`).
* If `indexStart >= str.length`, an empty string is returned.
* If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`.
* If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number(indexStart)`](../number)), it's treated as `0`.
* If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number(indexEnd)`](../number)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string.
* If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`.
* If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned.
Examples
--------
### Using slice() to create a new string
The following example uses `slice()` to create a new string.
```
const str1 = "The morning is upon us."; // The length of str1 is 23.
const str2 = str1.slice(1, 8);
const str3 = str1.slice(4, -2);
const str4 = str1.slice(12);
const str5 = str1.slice(30);
console.log(str2); // he morn
console.log(str3); // morning is upon u
console.log(str4); // is upon us.
console.log(str5); // ""
```
### Using slice() with negative indexes
The following example uses `slice()` with negative indexes.
```
const str = "The morning is upon us.";
str.slice(-3); // 'us.'
str.slice(-3, -1); // 'us'
str.slice(0, -1); // 'The morning is upon us'
str.slice(4, -1); // 'morning is upon us'
```
This example counts backwards from the end of the string by `11` to find the start index and forwards from the start of the string by `16` to find the end index.
```
console.log(str.slice(-11, 16)); // "is u"
```
Here it counts forwards from the start by `11` to find the start index and backwards from the end by `7` to find the end index.
```
console.log(str.slice(11, -7)); // " is u"
```
These arguments count backwards from the end by `5` to find the start index and backwards from the end by `1` to find the end index.
```
console.log(str.slice(-5, -1)); // "n us"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.slice](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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
--------
* [`String.prototype.substr()`](substr)
* [`String.prototype.substring()`](substring)
* [`Array.prototype.slice()`](../array/slice)
| programming_docs |
javascript String.prototype.italics() String.prototype.italics()
==========================
**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.
The `italics()` method creates a string that embeds a string in an [`<i>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i) element (`<i>str</i>`), which causes a string to be displayed as italic.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
italics()
```
### Return value
A string beginning with an `<i>` start tag, then the text `str`, and then an `</i>` end tag.
Examples
--------
### Using italics()
The following example uses deprecated string methods to change the formatting of a string:
```
const worldString = "Hello, world";
console.log(worldString.blink()); // <blink>Hello, world</blink>
console.log(worldString.bold()); // <b>Hello, world</b>
console.log(worldString.italics()); // <i>Hello, world</i>
console.log(worldString.strike()); // <strike>Hello, world</strike>
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.italics](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.italics) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `italics` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.italics` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.blink()`](blink)
* [`String.prototype.bold()`](bold)
* [`String.prototype.strike()`](strike)
javascript String.prototype.fixed() String.prototype.fixed()
========================
**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.
The `fixed()` method creates a string that embeds a string in a [`<tt>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tt) element (`<tt>str</tt>`), which causes a string to be displayed in a fixed-pitch font.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
fixed()
```
### Return value
A string beginning with a `<tt>` start tag, then the text `str`, and then a `</tt>` end tag.
Examples
--------
### Using fixed()
The following example uses the `fixed` method to change the formatting of a string:
```
const worldString = "Hello, world";
console.log(worldString.fixed()); // "<tt>Hello, world</tt>"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.fixed](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.fixed) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fixed` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.fixed` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.bold()`](bold)
* [`String.prototype.italics()`](italics)
* [`String.prototype.strike()`](strike)
javascript String.prototype.match() String.prototype.match()
========================
The `match()` method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).
Try it
------
Syntax
------
```
match(regexp)
```
### Parameters
`regexp` A regular expression object, or any object that has a [`Symbol.match`](../symbol/match) method.
If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a [`RegExp`](../regexp) by using `new RegExp(regexp)`.
If you don't give any parameter and use the `match()` method directly, you will get an [`Array`](../array) with an empty string: `[""]`, because this is equivalent to `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()`](../regexp/exec) (an array with some extra properties).
Description
-----------
The implementation of `String.prototype.match` itself is very simple β it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](../regexp/@@match).
* If you need to know if a string matches a regular expression [`RegExp`](../regexp), use [`RegExp.prototype.test()`](../regexp/test).
* If you only want the first match found, you might want to use [`RegExp.prototype.exec()`](../regexp/exec) instead.
* If you want to obtain capture groups and the global flag is set, you need to use [`RegExp.prototype.exec()`](../regexp/exec) or [`String.prototype.matchAll()`](matchall) instead.
For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](../regexp/@@match).
Examples
--------
### Using match()
In the following example, `match()` is used to find `"Chapter"` followed by one or more numeric characters followed by a decimal point and numeric character zero or more times.
The regular expression includes the `i` flag so that upper/lower case differences will be ignored.
```
const str = "For more information, see Chapter 3.4.5.1";
const re = /see (chapter \d+(\.\d)\*)/i;
const found = str.match(re);
console.log(found);
// [
// 'see Chapter 3.4.5.1',
// 'Chapter 3.4.5.1',
// '.1',
// index: 22,
// input: 'For more information, see Chapter 3.4.5.1',
// groups: undefined
// ]
```
In the match result above, `'see Chapter 3.4.5.1'` is the whole match. `'Chapter 3.4.5.1'` was captured by `(chapter \d+(\.\d)*)`. `'.1'` was the last value captured by `(\.\d)`. The `index` property (`22`) is the zero-based index of the whole match. The `input` property is the original string that was parsed.
### Using global and ignoreCase flags with match()
The following example demonstrates the use of the global flag and ignore-case flag with `match()`. All letters `A` through `E` and `a` through `e` are returned, each its own element in the array.
```
const str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const regexp = /[A-E]/gi;
const matches = str.match(regexp);
console.log(matches);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
```
**Note:** See also [`String.prototype.matchAll()`](matchall) and [Advanced searching with flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags).
### Using named capturing groups
In browsers which support named capturing groups, the following code captures `"fox"` or `"cat"` into a group named `animal`:
```
const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";
const capturingRegex = /(?<animal>fox|cat) jumps over/;
const found = paragraph.match(capturingRegex);
console.log(found.groups); // {animal: "fox"}
```
### Using match() with no parameter
```
const str = "Nothing will come of nothing.";
str.match(); // returns [""]
```
### Using match() with a non-RegExp implementing @@match
If an object has a `Symbol.match` method, it can be used as a custom matcher. The return value of `Symbol.match` becomes the return value of `match()`.
```
const str = "Hmm, this is interesting.";
str.match({
[Symbol.match](str) {
return ["Yes, it's interesting."];
},
}); // returns ["Yes, it's interesting."]
```
### A non-RegExp as the parameter
When the `regexp` parameter is a string or a number, it is implicitly converted to a [`RegExp`](../regexp) by using `new RegExp(regexp)`.
```
const str1 =
"NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.";
const str2 =
"My grandfather is 65 years old and My grandmother is 63 years old.";
const str3 = "The contract was declared null and void.";
str1.match("number"); // "number" is a string. returns ["number"]
str1.match(NaN); // the type of NaN is the number. returns ["NaN"]
str1.match(Infinity); // the type of Infinity is the number. returns ["Infinity"]
str1.match(+Infinity); // returns ["Infinity"]
str1.match(-Infinity); // returns ["-Infinity"]
str2.match(65); // returns ["65"]
str2.match(+65); // A number with a positive sign. returns ["65"]
str3.match(null); // returns ["null"]
```
This may have unexpected results if special characters are not properly escaped.
```
console.log("123".match("1.3")); // [ "123" ]
```
This is a match because `.` in a regex matches all characters. In order to make it only match the dot character, you need to escape the input.
```
console.log("123".match("1\\.3")); // null
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.match](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.match` in `core-js` with fixes and implementation of modern behavior like `Symbol.match` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.matchAll()`](matchall)
* [`RegExp`](../regexp)
* [`RegExp.prototype.exec()`](../regexp/exec)
* [`RegExp.prototype.test()`](../regexp/test)
javascript String.prototype.replaceAll() String.prototype.replaceAll()
=============================
The `replaceAll()` method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a [`RegExp`](../regexp), and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged.
Try it
------
Syntax
------
```
replaceAll(pattern, replacement)
```
### Parameters
`pattern` Can be a string or an object with a [`Symbol.replace`](../symbol/replace) method β the typical example being a [regular expression](../regexp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string.
If `pattern` [is a regex](includes), then it must have the global (`g`) flag set, or a [`TypeError`](../typeerror) is thrown.
`replacement` Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](replace).
### Return value
A new string, with all matches of a pattern replaced by a replacement.
### Exceptions
[`TypeError`](../typeerror) Thrown if the `pattern` [is a regex](../regexp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](../regexp/flags) property does not contain `"g"`).
Description
-----------
This method does not mutate the string value it's called on. It returns a new string.
Unlike [`replace()`](replace), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](../regexp/regexp) constructor without escaping special characters may unintentionally change its semantics.
```
function unsafeRedactName(text, name) {
return text.replace(new RegExp(name, "g"), "[REDACTED]");
}
function safeRedactName(text, name) {
return text.replaceAll(name, "[REDACTED]");
}
const report =
"A hacker called ha.\*er used special characters in their name to breach the system.";
console.log(unsafeRedactName(report, "ha.\*er")); // "A [REDACTED]s in their name to breach the system."
console.log(safeRedactName(report, "ha.\*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."
```
If `pattern` is an object with a [`Symbol.replace`](../symbol/replace) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `@@replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global).
If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`split()`](split) behavior.
```
"xxx".replaceAll("", "\_"); // "\_x\_x\_x\_"
```
For more information about how regex properties (especially the [sticky](../regexp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](../regexp/@@replace).
Examples
--------
### Using replaceAll()
```
"aabbcc".replaceAll("b", ".");
// 'aa..cc'
```
### Non-global regex throws
When using a regular expression search value, it must be global. This won't work:
```
"aabbcc".replaceAll(/b/, ".");
// TypeError: replaceAll must be called with a global RegExp
```
This will work:
```
"aabbcc".replaceAll(/b/g, ".");
("aa..cc");
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.replaceall](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.replaceall) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `replaceAll` | 85 | 85 | 77 | No | 71 | 13.1 | 85 | 85 | 79 | 60 | 13.4 | 14.0 | 1.2 | 15.0.0 |
See also
--------
* [Polyfill of `String.prototype.replaceAll` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.replace()`](replace)
* [`String.prototype.match()`](match)
* [`RegExp.prototype.exec()`](../regexp/exec)
* [`RegExp.prototype.test()`](../regexp/test)
javascript String.prototype.codePointAt() String.prototype.codePointAt()
==============================
The `codePointAt()` method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index.
Try it
------
Syntax
------
```
codePointAt(pos)
```
### Parameters
`pos` Position of an element in `str` to return the code point value from.
### Return value
A decimal number representing the code point value of the character at the given `pos`.
* If there is no element at `pos`, returns [`undefined`](../undefined).
* If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate *pair*.
* If the element at `pos` is a UTF-16 low surrogate, returns *only* the low surrogate code point.
Examples
--------
### Using codePointAt()
```
"ABC".codePointAt(0); // 65
"ABC".codePointAt(0).toString(16); // 41
"π".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0).toString(16); // 1f60d
"π".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1).toString(16); // de0d
"ABC".codePointAt(42); // undefined
```
### Looping with codePointAt()
Because indexing to a `pos` whose element is a UTF-16 low surrogate, returns *only* the low surrogate, it's better not to index directly into a UTF-16 string.
Instead, use a [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) statement or an Array's [`forEach()`](../array/foreach) method (or anything which correctly iterates UTF-16 surrogates) to iterate the string, using `codePointAt(0)` to get the code point of each element.
```
for (const codePoint of "\ud83d\udc0e\ud83d\udc71\u2764") {
console.log(codePoint.codePointAt(0).toString(16));
}
// '1f40e', '1f471', '2764'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.codepointat](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.codepointat) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `codePointAt` | 41 | 12 | 29 | No | 28 | 9 | 41 | 41 | 29 | 28 | 9 | 4.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `String.prototype.codePointAt` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.fromCodePoint()`](fromcodepoint)
* [`String.fromCharCode()`](fromcharcode)
* [`String.prototype.charCodeAt()`](charcodeat)
* [`String.prototype.charAt()`](charat)
javascript String.prototype.includes() String.prototype.includes()
===========================
The `includes()` method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate.
Try it
------
Syntax
------
```
includes(searchString)
includes(searchString, position)
```
### Parameters
`searchString` A string to be searched for within `str`. Cannot be a regex.
`position` Optional
The position within the string at which to begin searching for `searchString`. (Defaults to `0`.)
### Return value
`true` if the search string is found anywhere within the given string, including when `searchString` is an empty string; otherwise, `false`.
### Exceptions
[`TypeError`](../typeerror) If `searchString` [is a regex](../regexp#special_handling_for_regexes).
Description
-----------
This method lets you determine whether or not a string includes another string.
### Case-sensitivity
The `includes()` method is case sensitive. For example, the following expression returns `false`:
```
"Blue Whale".includes("blue"); // returns false
```
You can work around this constraint by transforming both the original string and the search string to all lowercase:
```
"Blue Whale".toLowerCase().includes("blue"); // returns true
```
Examples
--------
### Using includes()
```
const str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("nonexistent")); // false
console.log(str.includes("To be", 1)); // false
console.log(str.includes("TO BE")); // false
console.log(str.includes("")); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.includes](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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` | 41 | 12 | 40
18-48 | No | 28 | 9 | 41 | 41 | 40
18-48 | 28 | 9 | 4.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `String.prototype.includes` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`Array.prototype.includes()`](../array/includes)
* [`TypedArray.prototype.includes()`](../typedarray/includes)
* [`String.prototype.indexOf()`](indexof)
* [`String.prototype.lastIndexOf()`](lastindexof)
* [`String.prototype.startsWith()`](startswith)
* [`String.prototype.endsWith()`](endswith)
| programming_docs |
javascript String.prototype.trimEnd() String.prototype.trimEnd()
==========================
The `trimEnd()` method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method.
Try it
------
Syntax
------
```
trimEnd()
trimRight()
```
### Return value
A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](../../lexical_grammar#white_space) characters plus [line terminators](../../lexical_grammar#line_terminators).
If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`).
### Aliasing
After [`trim()`](trim) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`padEnd()`](padend), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means:
```
String.prototype.trimRight.name === "trimEnd";
```
Examples
--------
### Using trimEnd()
The following example trims whitespace from the end of `str`, but not from its start.
```
let str = " foo ";
console.log(str.length); // 8
str = str.trimEnd();
console.log(str.length); // 6
console.log(str); // ' foo'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.trimend](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.trimend) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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 |
See also
--------
* [Polyfill of `String.prototype.trimEnd` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.trim()`](trim)
* [`String.prototype.trimStart()`](trimstart)
javascript String.raw() String.raw()
============
The `String.raw()` static method is a tag function of [template literals](../../template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals β that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not.
Try it
------
Syntax
------
```
String.raw(strings, ...substitutions)
String.raw`templateString`
```
### Parameters
`strings` Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings.
`...substitutions` Contains substitution values.
`templateString` A [template literal](../../template_literals), optionally with substitutions (`${...}`).
### Return value
The raw string form of a given template literal.
### Exceptions
[`TypeError`](../typeerror) Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`.
Description
-----------
In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](../../template_literals#tagged_templates)).
`String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code.
**Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](#building_an_identity_tag) for how to implement this.
If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders β which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings.
Examples
--------
### Using String.raw()
```
String.raw`Hi\n${2 + 3}!`;
// 'Hi\\n5!', the character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.
String.raw`Hi\u000A!`;
// 'Hi\\u000A!', same here, this time we will get the
// \, u, 0, 0, 0, A, 6 characters.
// All kinds of escape characters will be ineffective
// and backslashes will be present in the output string.
// You can confirm this by checking the .length property
// of the string.
const name = "Bob";
String.raw`Hi\n${name}!`;
// 'Hi\\nBob!', substitutions are processed.
String.raw`Hi \${name}!`;
// 'Hi \\${name}!', the dollar sign is escaped; there's no interpolation.
```
### Building an identity tag
Many tools give special treatment to literals tagged by a particular name.
```
// 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>
`;
```
One might naΓ―vely implement the `html` tag as:
```
const html = String.raw;
```
This, in fact, works for the case above. However, because `String.raw` would concatenate the *raw* string literals instead of the "cooked" ones, escape sequences would not be processed.
```
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\\n</canvas>"
```
This may not be what you want for a "true identity" tag, where the tag is purely for markup and doesn't change the literal's value. In this case, you can create a custom tag and pass the "cooked" (i.e. escape sequences are processed) literal array to `String.raw`, pretending they are raw strings.
```
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);
// Some formatters will format this literal's content as HTML
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\n</canvas>"; the "\n" becomes a line break
```
Notice the first argument is an object with a `raw` property, whose value is an array-like object (with a `length` property and integer indexes) representing the separated strings in the template literal. The rest of the arguments are the substitutions. Since the `raw` value can be any array-like object, it can even be a string! For example, `'test'` is treated as `['t', 'e', 's', 't']`. The following is equivalent to ``t${0}e${1}s${2}t``:
```
String.raw({ raw: "test" }, 0, 1, 2); // 't0e1s2t'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.raw](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.raw) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `raw` | 41 | 12 | 34 | No | 28 | 9 | 41 | 41 | 34 | 28 | 9 | 4.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `String.raw` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [Template literals](../../template_literals)
* [`String`](../string)
* [Lexical grammar](../../lexical_grammar)
javascript String.prototype.padStart() String.prototype.padStart()
===========================
The `padStart()` method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
Try it
------
Syntax
------
```
padStart(targetLength)
padStart(targetLength, padString)
```
### Parameters
`targetLength` The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is.
`padString` Optional
The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020).
### Return value
A [`String`](../string) of the specified `targetLength` with `padString` applied from the start.
Examples
--------
### Basic examples
```
"abc".padStart(10); // " abc"
"abc".padStart(10, "foo"); // "foofoofabc"
"abc".padStart(6, "123465"); // "123abc"
"abc".padStart(8, "0"); // "00000abc"
"abc".padStart(1); // "abc"
```
### Fixed width string number conversion
```
// JavaScript version of: (unsigned)
// printf "%0\*d" width num
function leftFillNum(num, targetLength) {
return num.toString().padStart(targetLength, 0);
}
const num = 123;
console.log(leftFillNum(num, 5)); // "00123"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.padstart](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.padstart) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `padStart` | 57 | 15 | 48 | No | 44 | 10 | 57 | 57 | 48 | 43 | 10 | 7.0 | 1.0 | 8.0.0
7.0.0 |
See also
--------
* [Polyfill of `String.prototype.padStart` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.padEnd()`](padend)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/string.polyfill.js)
javascript String.prototype.big() String.prototype.big()
======================
**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.
The `big()` method creates a string that embeds a string in a [`<big>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/big) element (`<big>str</big>`), which causes a string to be displayed in a big font.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `big()`, the `<big>` element itself has been removed in [HTML5](https://developer.mozilla.org/en-US/docs/Glossary/HTML5) and shouldn't be used anymore. Web developers should use [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) properties Instead.
Syntax
------
```
big()
```
### Return value
A string beginning with a `<big>` start tag, then the text `str`, and then a `</big>` end tag.
Examples
--------
### Using big()
The following example uses string methods to change the size of a string:
```
const worldString = "Hello, world";
console.log(worldString.small()); // <small>Hello, world</small>
console.log(worldString.big()); // <big>Hello, world</big>
console.log(worldString.fontsize(7)); // <font size="7">Hello, world</font>
```
With the [`element.style`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) object you can get the element's `style` attribute and manipulate it more generically, for example:
```
document.getElementById("yourElemId").style.fontSize = "2em";
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.big](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.big) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `big` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.big` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.fontsize()`](fontsize)
* [`String.prototype.small()`](small)
javascript String.prototype.search() String.prototype.search()
=========================
The `search()` method executes a search for a match between a regular expression and this [`String`](../string) object.
Try it
------
Syntax
------
```
search(regexp)
```
### Parameters
`regexp` A regular expression object, or any object that has a [`Symbol.search`](../symbol/search) method.
If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a [`RegExp`](../regexp) by using `new RegExp(regexp)`.
### Return value
The index of the first match between the regular expression and the given string, or `-1` if no match was found.
Description
-----------
The implementation of `String.prototype.search()` itself is very simple β it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](../regexp/@@search).
The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](../regexp/@@search).
When you want to know whether a pattern is found, and *also* know its index within a string, use `search()`.
* If you only want to know if it exists, use the [`RegExp.prototype.test()`](../regexp/test) method, which returns a boolean.
* If you need the content of the matched text, use [`match()`](match) or [`RegExp.prototype.exec()`](../regexp/exec).
Examples
--------
### Using search()
The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (`-1`).
```
const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.search](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `flags` | No | No | 1-49 | No | No | No | No | No | 4-49 | No | No | No | No | No |
See also
--------
* [Polyfill of `String.prototype.search` in `core-js` with fixes and implementation of modern behavior like `Symbol.search` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [Using regular expressions in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
* [`String.prototype.match()`](match)
* [`RegExp.prototype.exec()`](../regexp/exec)
* [`RegExp.prototype[@@search]()`](../regexp/@@search)
javascript String.prototype.indexOf() String.prototype.indexOf()
==========================
The `indexOf()` method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number.
Try it
------
Syntax
------
```
indexOf(searchString)
indexOf(searchString, position)
```
### Parameters
`searchString` Substring to search for, [coerced to a string](../string#string_coercion).
If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` β because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` β because the substring `"undefined"` is not found in the string `"undefine"`.
`position` Optional
The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`.
* `'hello world hello'.indexOf('o', -5)` returns `4` β because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`.
* `'hello world hello'.indexOf('world', 12)` returns `-1` β because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`.
* `'hello world hello'.indexOf('o', 99)` returns `-1` β because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all.
### Return value
The index of the first occurrence of `searchString` found, or `-1` if not found.
#### Return value when using an empty search string
Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument:
```
"hello world".indexOf(""); // returns 0
"hello world".indexOf("", 0); // returns 0
"hello world".indexOf("", 3); // returns 3
"hello world".indexOf("", 8); // returns 8
```
However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length:
```
"hello world".indexOf("", 11); // returns 11
"hello world".indexOf("", 13); // returns 11
"hello world".indexOf("", 22); // returns 11
```
In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.
Description
-----------
Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1.
```
"Blue Whale".indexOf("Blue"); // returns 0
"Blue Whale".indexOf("Blute"); // returns -1
"Blue Whale".indexOf("Whale", 0); // returns 5
"Blue Whale".indexOf("Whale", 5); // returns 5
"Blue Whale".indexOf("Whale", 7); // returns -1
"Blue Whale".indexOf(""); // returns 0
"Blue Whale".indexOf("", 9); // returns 9
"Blue Whale".indexOf("", 10); // returns 10
"Blue Whale".indexOf("", 11); // returns 10
```
The `indexOf()` method is case sensitive. For example, the following expression returns `-1`:
```
"Blue Whale".indexOf("blue"); // returns -1
```
### Checking occurrences
When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`:
```
"Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale'
"Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale'
```
Examples
--------
### Using indexOf()
The following example uses `indexOf()` to locate substrings in the string `"Brave new world"`.
```
const str = "Brave new world";
console.log(str.indexOf("w")); // 8
console.log(str.indexOf("new")); // 6
```
### indexOf() and case-sensitivity
The following example defines two string variables.
The variables contain the same string, except that the second string contains uppercase letters. The first [`console.log()`](https://developer.mozilla.org/en-US/docs/Web/API/console/log) method displays `19`. But because the `indexOf()` method is case sensitive, the string `"cheddar"` is not found in `myCapString`, so the second `console.log()` method displays `-1`.
```
const myString = "brie, pepper jack, cheddar";
const myCapString = "Brie, Pepper Jack, Cheddar";
console.log(myString.indexOf("cheddar")); // 19
console.log(myCapString.indexOf("cheddar")); // -1
```
### Using indexOf() to count occurrences of a letter in a string
The following example sets `count` to the number of occurrences of the letter `e` in the string `str`:
```
const str = "To be, or not to be, that is the question.";
let count = 0;
let position = str.indexOf("e");
while (position !== -1) {
count++;
position = str.indexOf("e", position + 1);
}
console.log(count); // 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.indexof](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.charAt()`](charat)
* [`String.prototype.lastIndexOf()`](lastindexof)
* [`String.prototype.includes()`](includes)
* [`String.prototype.split()`](split)
* [`Array.prototype.indexOf()`](../array/indexof)
| programming_docs |
javascript String.prototype.small() String.prototype.small()
========================
**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.
The `small()` method creates a string that embeds a string in a [`<small>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small) element (`<small>str</small>`), which causes a string to be displayed in a small font.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
small()
```
### Return value
A string beginning with a `<small>` start tag, then the text `str`, and then a `</small>` end tag.
Examples
--------
### Using small()
The following example uses string methods to change the size of a string:
```
const worldString = "Hello, world";
console.log(worldString.small()); // <small>Hello, world</small>
console.log(worldString.big()); // <big>Hello, world</big>
console.log(worldString.fontsize(7)); // <font size="7">Hello, world</fontsize>
```
With the [`element.style`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) object you can get the element's `style` attribute and manipulate it more generically, for example:
```
document.getElementById("yourElemId").style.fontSize = "0.7em";
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.small](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.small) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `small` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.small` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.fontsize()`](fontsize)
* [`String.prototype.big()`](big)
javascript String.prototype.toString() String.prototype.toString()
===========================
The `toString()` method returns a string representing the specified string value.
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the specified string value.
Description
-----------
The [`String`](../string) object overrides the `toString` method of [`Object`](../object); it does not inherit [`Object.prototype.toString()`](../object/tostring). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](valueof).
The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../typeerror) for other `this` values without attempting to coerce them to string values.
Because `String` doesn't have a [`[@@toPrimitive]()`](../symbol/toprimitive) method, JavaScript calls the `toString()` method automatically when a `String` *object* is used in a context expecting a string, such as in a [template literal](../../template_literals). However, String *primitive* values do not consult the `toString()` method to be [coerced to strings](../string#string_coercion) β since they are already strings, no conversion is performed.
```
String.prototype.toString = () => "Overridden";
console.log(`${"foo"}`); // "foo"
console.log(`${new String("foo")}`); // "Overridden"
```
Examples
--------
### Using toString()
The following example displays the string value of a [`String`](../string) object:
```
const x = new String("Hello world");
console.log(x.toString()); // "Hello world"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.tostring](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.valueOf()`](valueof)
javascript String.prototype.normalize() String.prototype.normalize()
============================
The `normalize()` method returns the Unicode Normalization Form of the string.
Try it
------
Syntax
------
```
normalize()
normalize(form)
```
### Parameters
`form` Optional
One of `"NFC"`, `"NFD"`, `"NFKC"`, or `"NFKD"`, specifying the Unicode Normalization Form. If omitted or [`undefined`](../undefined), `"NFC"` is used.
These values have the following meanings:
`"NFC"` Canonical Decomposition, followed by Canonical Composition.
`"NFD"` Canonical Decomposition.
`"NFKC"` Compatibility Decomposition, followed by Canonical Composition.
`"NFKD"` Compatibility Decomposition.
### Return value
A string containing the Unicode Normalization Form of the given string.
### Errors thrown
[`RangeError`](../rangeerror) A [`RangeError`](../rangeerror) is thrown if `form` isn't one of the values specified above.
Description
-----------
Unicode assigns a unique numerical value, called a *code point*, to each character. For example, the code point for `"A"` is given as U+0041. However, sometimes more than one code point, or sequence of code points, can represent the same abstract character β the character `"Γ±"` for example can be represented by either of:
* The single code point U+00F1.
* The code point for `"n"` (U+006E) followed by the code point for the combining tilde (U+0303).
```
const string1 = "\u00F1";
const string2 = "\u006E\u0303";
console.log(string1); // Γ±
console.log(string2); // Γ±
```
However, since the code points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths.
```
const string1 = "\u00F1"; // Γ±
const string2 = "\u006E\u0303"; // Γ±
console.log(string1 === string2); // false
console.log(string1.length); // 1
console.log(string2.length); // 2
```
The `normalize()` method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters. There are two main normalization forms, one based on **canonical equivalence** and the other based on **compatibility**.
### Canonical equivalence normalization
In Unicode, two sequences of code points have canonical equivalence if they represent the same abstract characters, and should always have the same visual appearance and behavior (for example, they should always be sorted in the same way).
You can use `normalize()` using the `"NFD"` or `"NFC"` arguments to produce a form of the string that will be the same for all canonically equivalent strings. In the example below we normalize two representations of the character `"Γ±"`:
```
let string1 = "\u00F1"; // Γ±
let string2 = "\u006E\u0303"; // Γ±
string1 = string1.normalize("NFD");
string2 = string2.normalize("NFD");
console.log(string1 === string2); // true
console.log(string1.length); // 2
console.log(string2.length); // 2
```
#### Composed and decomposed forms
Note that the length of the normalized form under `"NFD"` is `2`. That's because `"NFD"` gives you the **decomposed** version of the canonical form, in which single code points are split into multiple combining ones. The decomposed canonical form for `"Γ±"` is `"\u006E\u0303"`.
You can specify `"NFC"` to get the **composed** canonical form, in which multiple code points are replaced with single code points where possible. The composed canonical form for `"Γ±"` is `"\u00F1"`:
```
let string1 = "\u00F1"; // Γ±
let string2 = "\u006E\u0303"; // Γ±
string1 = string1.normalize("NFC");
string2 = string2.normalize("NFC");
console.log(string1 === string2); // true
console.log(string1.length); // 1
console.log(string2.length); // 1
console.log(string2.codePointAt(0).toString(16)); // f1
```
### Compatibility normalization
In Unicode, two sequences of code points are compatible if they represent the same abstract characters, and should be treated alike in some β but not necessarily all β applications.
All canonically equivalent sequences are also compatible, but not vice versa.
For example:
* the code point U+FB00 represents the [ligature](https://developer.mozilla.org/en-US/docs/Glossary/Ligature) `"ο¬"`. It is compatible with two consecutive U+0066 code points (`"ff"`).
* the code point U+24B9 represents the symbol `"βΉ"`. It is compatible with the U+0044 code point (`"D"`).
In some respects (such as sorting) they should be treated as equivalentβand in some (such as visual appearance) they should not, so they are not canonically equivalent.
You can use `normalize()` using the `"NFKD"` or `"NFKC"` arguments to produce a form of the string that will be the same for all compatible strings:
```
let string1 = "\uFB00";
let string2 = "\u0066\u0066";
console.log(string1); // ο¬
console.log(string2); // ff
console.log(string1 === string2); // false
console.log(string1.length); // 1
console.log(string2.length); // 2
string1 = string1.normalize("NFKD");
string2 = string2.normalize("NFKD");
console.log(string1); // ff <- visual appearance changed
console.log(string2); // ff
console.log(string1 === string2); // true
console.log(string1.length); // 2
console.log(string2.length); // 2
```
When applying compatibility normalization it's important to consider what you intend to do with the strings, since the normalized form may not be appropriate for all applications. In the example above the normalization is appropriate for search, because it enables a user to find the string by searching for `"f"`. But it may not be appropriate for display, because the visual representation is different.
As with canonical normalization, you can ask for decomposed or composed compatible forms by passing `"NFKD"` or `"NFKC"`, respectively.
Examples
--------
### Using normalize()
```
// Initial string
// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
// U+0323: COMBINING DOT BELOW
const str = "\u1E9B\u0323";
// Canonically-composed form (NFC)
// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
// U+0323: COMBINING DOT BELOW
str.normalize("NFC"); // '\u1E9B\u0323'
str.normalize(); // same as above
// Canonically-decomposed form (NFD)
// U+017F: LATIN SMALL LETTER LONG S
// U+0323: COMBINING DOT BELOW
// U+0307: COMBINING DOT ABOVE
str.normalize("NFD"); // '\u017F\u0323\u0307'
// Compatibly-composed (NFKC)
// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
str.normalize("NFKC"); // '\u1E69'
// Compatibly-decomposed (NFKD)
// U+0073: LATIN SMALL LETTER S
// U+0323: COMBINING DOT BELOW
// U+0307: COMBINING DOT ABOVE
str.normalize("NFKD"); // '\u0073\u0323\u0307'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.normalize](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.normalize) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `normalize` | 34 | 12 | 31 | No | 21 | 10 | 37 | 34 | 31 | 21 | 10 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Unicode Standard Annex #15, Unicode Normalization Forms](https://www.unicode.org/reports/tr15/)
* [Unicode equivalence](https://en.wikipedia.org/wiki/Unicode_equivalence)
javascript String.prototype.startsWith() String.prototype.startsWith()
=============================
The `startsWith()` method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate.
Try it
------
Syntax
------
```
startsWith(searchString)
startsWith(searchString, position)
```
### Parameters
`searchString` The characters to be searched for at the start of this string. Cannot be a regex.
`position` Optional
The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`.
### Return value
`true` if the given characters are found at the beginning of the string, including when `searchString` is an empty string; otherwise, `false`.
### Exceptions
[`TypeError`](../typeerror) If `searchString` [is a regex](../regexp#special_handling_for_regexes).
Description
-----------
This method lets you determine whether or not a string begins with another string. This method is case-sensitive.
Examples
--------
### Using startsWith()
```
const str = "To be, or not to be, that is the question.";
console.log(str.startsWith("To be")); // true
console.log(str.startsWith("not to be")); // false
console.log(str.startsWith("not to be", 10)); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.startswith](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.startswith) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `startsWith` | 41 | 12 | 17 | No | 28 | 9 | 37 | 36 | 17 | 24 | 9 | 3.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `String.prototype.startsWith` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.endsWith()`](endswith)
* [`String.prototype.includes()`](includes)
* [`String.prototype.indexOf()`](indexof)
* [`String.prototype.lastIndexOf()`](lastindexof)
javascript String.prototype.strike() String.prototype.strike()
=========================
**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.
The `strike()` method creates a string that embeds a string in a [`<strike>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strike) element (`<strike>str</strike>`), which causes a string to be displayed as struck-out text.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
strike()
```
### Return value
A string beginning with a `<strike>` start tag, then the text `str`, and then a `</strike>` end tag.
Examples
--------
### Using strike()
The following example uses deprecated string methods to change the formatting of a string:
```
const worldString = "Hello, world";
console.log(worldString.blink()); // <blink>Hello, world</blink>
console.log(worldString.bold()); // <b>Hello, world</b>
console.log(worldString.italics()); // <i>Hello, world</i>
console.log(worldString.strike()); // <strike>Hello, world</strike>
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.strike](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.strike) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `strike` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.strike` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.blink()`](blink)
* [`String.prototype.bold()`](bold)
* [`String.prototype.italics()`](italics)
javascript String.prototype.concat() String.prototype.concat()
=========================
The `concat()` method concatenates the string arguments to the calling string and returns a new string.
Try it
------
Syntax
------
```
concat(str1)
concat(str1, str2)
concat(str1, str2, /\* β¦, \*/ strN)
```
### Parameters
`strN` One or more strings to concatenate to `str`.
### Return value
A new string containing the combined text of the strings provided.
Description
-----------
The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other.
If the arguments are not of the type string, they are converted to string values before concatenating.
The `concat()` method is very similar to the [addition/string concatenation operators](../../operators/addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](../string#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](../../operators/addition).
Examples
--------
### Using concat()
The following example combines strings into a new string.
```
const hello = "Hello, ";
console.log(hello.concat("Kevin", ". Have a nice day."));
// Hello, Kevin. Have a nice day.
const greetList = ["Hello", " ", "Venkat", "!"];
"".concat(...greetList); // "Hello Venkat!"
"".concat({}); // "[object Object]"
"".concat([]); // ""
"".concat(null); // "null"
"".concat(true); // "true"
"".concat(4, 5); // "45"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.concat](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.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 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array.prototype.concat()`](../array/concat)
* [Addition operator](../../operators/addition)
| programming_docs |
javascript String.prototype.substr() String.prototype.substr()
=========================
**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.
The `substr()` method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.
**Note:** `substr()` is not part of the main ECMAScript specification β it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](substring) and [`String.prototype.slice()`](slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](substring#the_difference_between_substring_and_substr) has some comparisons between the three methods.
Try it
------
Syntax
------
```
substr(start)
substr(start, length)
```
### Parameters
`start` The index of the first character to include in the returned substring.
`length` Optional
The number of characters to extract.
### Return value
A new string containing the specified part of the given string.
Description
-----------
A string's `substr()` method extracts `length` characters from the string, counting from the `start` index.
* If `start >= str.length`, an empty string is returned.
* If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`.
* If `start` is omitted or [`undefined`](../undefined), it's treated as `0`.
* If `length` is omitted or [`undefined`](../undefined), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string.
* If `length < 0`, an empty string is returned.
* For both `start` and `length`, [`NaN`](../nan) is treated as `0`.
Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` β `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`.
Examples
--------
### Using substr()
```
const aString = "Mozilla";
console.log(aString.substr(0, 1)); // 'M'
console.log(aString.substr(1, 0)); // ''
console.log(aString.substr(-1, 1)); // 'a'
console.log(aString.substr(1, -1)); // ''
console.log(aString.substr(-3)); // 'lla'
console.log(aString.substr(1)); // 'ozilla'
console.log(aString.substr(-20, 2)); // 'Mo'
console.log(aString.substr(20, 2)); // ''
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.substr](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.substr) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `substr` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.substr` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.slice()`](slice)
* [`String.prototype.substring()`](substring)
javascript String.prototype.fontsize() String.prototype.fontsize()
===========================
**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.
The `fontsize()` method creates a string that embeds a string in a [`<font>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font) element (`<font size="...">str</font>`), which causes a string to be displayed in the specified font size.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `fontsize()`, the `<font>` element itself has been removed in [HTML5](https://developer.mozilla.org/en-US/docs/Glossary/HTML5) and shouldn't be used anymore. Web developers should use [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) properties instead.
Syntax
------
```
fontsize(size)
```
### Parameters
`size` An integer between 1 and 7, or a string representing a signed integer between 1 and 7.
### Return value
A string beginning with a `<font size="size">` start tag (double quotes in `size` are replaced with `"`), then the text `str`, and then a `</font>` end tag.
Description
-----------
The `fontsize()` method itself simply joins the string parts together without any validation or normalization. However, to create valid [`<font>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font) elements, When you specify size as an integer, you set the font size of `str` to one of the 7 defined sizes. You can specify `size` as a string such as `"-2"` or `"+3"` to adjust the font size of `str` relative to 3, the default value.
Examples
--------
### Using fontsize()
The following example uses string methods to change the size of a string:
```
const worldString = "Hello, world";
console.log(worldString.small()); // <small>Hello, world</small>
console.log(worldString.big()); // <big>Hello, world</big>
console.log(worldString.fontsize(7)); // <font size="7">Hello, world</font>
```
With the [`element.style`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) object you can get the element's `style` attribute and manipulate it more generically, for example:
```
document.getElementById("yourElemId").style.fontSize = "0.7em";
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.fontsize](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.fontsize) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fontsize` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.fontsize` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.big()`](big)
* [`String.prototype.small()`](small)
javascript String.prototype.substring() String.prototype.substring()
============================
The `substring()` method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.
Try it
------
Syntax
------
```
substring(indexStart)
substring(indexStart, indexEnd)
```
### Parameters
`indexStart` The index of the first character to include in the returned substring.
`indexEnd` Optional
The index of the first character to exclude from the returned substring.
### Return value
A new string containing the specified part of the given string.
Description
-----------
`substring()` extracts characters from `indexStart` up to *but not including* `indexEnd`. In particular:
* If `indexEnd` is omitted, `substring()` extracts characters to the end of the string.
* If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string.
* If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below.
Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively.
Any argument value that is [`NaN`](../nan) is treated as if it were `0`.
Examples
--------
### Using substring()
The following example uses `substring()` to display characters from the string `'Mozilla'`:
```
const anyString = "Mozilla";
console.log(anyString.substring(0, 1)); // 'M'
console.log(anyString.substring(1, 0)); // 'M'
console.log(anyString.substring(0, 6)); // 'Mozill'
console.log(anyString.substring(4)); // 'lla'
console.log(anyString.substring(4, 7)); // 'lla'
console.log(anyString.substring(7, 4)); // 'lla'
console.log(anyString.substring(0, 7)); // 'Mozilla'
console.log(anyString.substring(0, 10)); // 'Mozilla'
```
### Using substring() with length property
The following example uses the `substring()` method and [`length`](length) property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.
```
const text = "Mozilla";
// Takes 4 last characters of string
console.log(text.substring(text.length - 4)); // prints "illa"
// Takes 5 last characters of string
console.log(text.substring(text.length - 5)); // prints "zilla"
```
### The difference between substring() and substr()
There are subtle differences between the `substring()` and [`substr()`](substr) methods, so you should be careful not to get them confused.
* The two parameters of `substr()` are `start` and `length`, while for `substring()`, they are `start` and `end`.
* `substr()`'s `start` index will wrap to the end of the string if it is negative, while `substring()` will clamp it to `0`.
* Negative lengths in `substr()` are treated as zero, while `substring()` will swap the two indexes if `end` is less than `start`.
Furthermore, `substr()` is considered a *legacy feature in ECMAScript*, so it is best to avoid using it if possible.
```
const text = "Mozilla";
console.log(text.substring(2, 5)); // "zil"
console.log(text.substr(2, 3)); // "zil"
```
### Differences between substring() and slice()
The `substring()` and [`slice()`](slice) methods are almost identical, but there are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.
The `substring()` method swaps its two arguments if `indexStart` is greater than `indexEnd`, meaning that a string is still returned. The [`slice()`](slice) method returns an empty string if this is the case.
```
const text = "Mozilla";
console.log(text.substring(5, 2)); // "zil"
console.log(text.slice(5, 2)); // ""
```
If either or both of the arguments are negative or `NaN`, the `substring()` method treats them as if they were `0`.
```
console.log(text.substring(-5, 2)); // "Mo"
console.log(text.substring(-5, -2)); // ""
```
`slice()` also treats `NaN` arguments as `0`, but when it is given negative values it counts backwards from the end of the string to find the indexes.
```
console.log(text.slice(-5, 2)); // ""
console.log(text.slice(-5, -2)); // "zil"
```
See the [`slice()`](slice) page for more examples with negative numbers.
### Replacing a substring within a string
The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string `Brave New World` to `Brave New Web`.
```
// Replaces oldS with newS in the string fullS
function replaceString(oldS, newS, fullS) {
for (let i = 0; i < fullS.length; ++i) {
if (fullS.substring(i, i + oldS.length) === oldS) {
fullS =
fullS.substring(0, i) +
newS +
fullS.substring(i + oldS.length, fullS.length);
}
}
return fullS;
}
replaceString("World", "Web", "Brave New World");
```
Note that this can result in an infinite loop if `oldS` is itself a substring of `newS` β for example, if you attempted to replace '`World`' with '`OtherWorld`' here.
A better method for replacing strings is as follows:
```
function replaceString(oldS, newS, fullS) {
return fullS.split(oldS).join(newS);
}
```
The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use [`String.prototype.replace()`](replace).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.substring](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.substring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `substring` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.substr()`](substr)
* [`String.prototype.slice()`](slice)
javascript String.prototype.sup() String.prototype.sup()
======================
**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.
The `sup()` method creates a string that embeds a string in a [`<sup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup) element (`<sup>str</sup>`), which causes a string to be displayed as superscript.
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
Syntax
------
```
sup()
```
### Return value
A string beginning with a `<sup>` start tag, then the text `str`, and then a `</sup>` end tag.
Examples
--------
### Using sub() and sup() methods
The following example uses the [`sub()`](sub) and `sup()` methods to format a string:
```
const superText = "superscript";
const subText = "subscript";
console.log(`This is what a ${superText.sup()} looks like.`);
// "This is what a <sup>superscript</sup> looks like."
console.log(`This is what a ${subText.sub()} looks like.`);
// "This is what a <sub>subscript</sub> looks like."
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.sup](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.sup) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sup` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `String.prototype.sup` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.sub()`](sub)
javascript String.prototype.charAt() String.prototype.charAt()
=========================
The [`String`](../string) object's `charAt()` method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.
Try it
------
Syntax
------
```
charAt(index)
```
### Parameters
`index` An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned.
### Return value
A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string.
Description
-----------
Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last characterβin a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string.
If no `index` is provided to `charAt()`, the default is `0`.
Examples
--------
### Displaying characters at different locations in a string
The following example displays characters at different locations in the string "`Brave new world`":
```
const anyString = "Brave new world";
console.log(`The character at index 0 is '${anyString.charAt()}'`);
// No index was provided, used 0 as default
console.log(`The character at index 0 is '${anyString.charAt(0)}'`);
console.log(`The character at index 1 is '${anyString.charAt(1)}'`);
console.log(`The character at index 2 is '${anyString.charAt(2)}'`);
console.log(`The character at index 3 is '${anyString.charAt(3)}'`);
console.log(`The character at index 4 is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
```
These lines display the following:
```
The character at index 0 is 'B'
The character at index 0 is 'B'
The character at index 1 is 'r'
The character at index 2 is 'a'
The character at index 3 is 'v'
The character at index 4 is 'e'
The character at index 999 is ''
```
### Getting whole characters
The following provides a means of ensuring that going through a string loop always provides a whole character, even if the string contains characters that are not in the Basic Multi-lingual Plane.
```
const str = "A\uD87E\uDC04Z"; // We could also use a non-BMP character directly
for (let i = 0; i < str.length; i++) {
let chr;
[chr, i] = getWholeCharAndI(str, i);
// Adapt this line at the top of each loop, passing in the whole string and
// the current iteration and returning an array with the individual character
// and 'i' value (only changed if a surrogate pair)
console.log(chr);
}
function getWholeCharAndI(str, i) {
const code = str.charCodeAt(i);
if (Number.isNaN(code)) {
return ""; // Position not found
}
if (code < 0xd800 || code > 0xdfff) {
return [str.charAt(i), i]; // Normal character, keeping 'i' the same
}
// High surrogate (could change last hex to 0xDB7F to treat high private
// surrogates as single characters)
if (0xd800 <= code && code <= 0xdbff) {
if (str.length <= i + 1) {
throw new Error("High surrogate without following low surrogate");
}
const next = str.charCodeAt(i + 1);
if (next < 0xdc00 || next > 0xdfff) {
throw new Error("High surrogate without following low surrogate");
}
return [str.charAt(i) + str.charAt(i + 1), i + 1];
}
// Low surrogate (0xDC00 <= code && code <= 0xDFFF)
if (i === 0) {
throw new Error("Low surrogate without preceding high surrogate");
}
const prev = str.charCodeAt(i - 1);
// (could change last hex to 0xDB7F to treat high private surrogates
// as single characters)
if (prev < 0xd800 || prev > 0xdbff) {
throw new Error("Low surrogate without preceding high surrogate");
}
// Return the next character instead (and increment)
return [str.charAt(i + 1), i + 1];
}
```
### Fixing charAt() to support non-Basic-Multilingual-Plane (BMP) characters
While the previous example may be more useful for programs that must support non-BMP characters (since it does not require the caller to know where any non-BMP character might appear), in the event that one *does* wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one can use the following:
```
function fixedCharAt(str, idx) {
str = String(str);
const surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
while (surrogatePairs.exec(str) !== null) {
const lastIdx = surrogatePairs.lastIndex;
if (lastIdx - 2 < idx) {
idx++;
} else {
break;
}
}
if (idx >= str.length || idx < 0) {
return "";
}
let ret = str.charAt(idx);
if (
/[\uD800-\uDBFF]/.test(ret) &&
/[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))
) {
// Go one further, since one of the "characters" is part of a surrogate pair
ret += str.charAt(idx + 1);
}
return ret;
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.charat](https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.charat) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `charAt` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.indexOf()`](indexof)
* [`String.prototype.lastIndexOf()`](lastindexof)
* [`String.prototype.charCodeAt()`](charcodeat)
* [`String.prototype.codePointAt()`](codepointat)
* [`String.prototype.split()`](split)
* [`String.fromCodePoint()`](fromcodepoint)
* [JavaScript has a Unicode problem β Mathias Bynens](https://mathiasbynens.be/notes/javascript-unicode)
| programming_docs |
javascript String.prototype.anchor() String.prototype.anchor()
=========================
**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.
The `anchor()` method creates a string that embeds a string in an [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element with a name (`<a name="...">str</a>`).
**Note:** All [HTML wrapper methods](../string#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. 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.
The HTML specification no longer allows the [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element to have a `name` attribute, so this method doesn't even create valid markup.
Syntax
------
```
anchor(name)
```
### Parameters
`name` A string representing a `name` value to put into the generated `<a name="...">` start tag.
### Return value
A string beginning with an `<a name="name">` start tag (double quotes in `name` are replaced with `"`), then the text `str`, and then an `</a>` end tag.
Examples
--------
### Using anchor()
```
const myString = "Table of Contents";
document.body.innerHTML = myString.anchor("contents\_anchor");
```
will output the following HTML:
```
<a name="contents\_anchor">Table of Contents</a>
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string.prototype.anchor](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.anchor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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 |
See also
--------
* [Polyfill of `String.prototype.anchor` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.link()`](link)
javascript AsyncFunction() constructor AsyncFunction() constructor
===========================
The `AsyncFunction()` constructor creates a new [`AsyncFunction`](../asyncfunction) object. In JavaScript, every [async function](../../statements/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;
```
The `AsyncFunction()` constructor is not intended to be used directly, and all caveats mentioned in the [`Function()`](../function/function) description apply to `AsyncFunction()`.
Syntax
------
```
new AsyncFunction(functionBody)
new AsyncFunction(arg0, functionBody)
new AsyncFunction(arg0, arg1, functionBody)
new AsyncFunction(arg0, arg1, /\* β¦ ,\*/ argN, functionBody)
AsyncFunction(functionBody)
AsyncFunction(arg0, functionBody)
AsyncFunction(arg0, arg1, functionBody)
AsyncFunction(arg0, arg1, /\* β¦ ,\*/ argN, functionBody)
```
**Note:** `AsyncFunction()` can be called with or without [`new`](../../operators/new). Both create a new `AsyncFunction` instance.
### Parameters
See [`Function()`](../function/function).
Examples
--------
### Creating an async function from an AsyncFunction() constructor
```
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
const AsyncFunction = async function () {}.constructor;
const fn = new AsyncFunction(
"a",
"b",
"return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);",
);
fn(10, 20).then((v) => {
console.log(v); // prints 30 after 4 seconds
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-async-function-constructor](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-async-function-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 |
| `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()` constructor](../function/function)
javascript EvalError() constructor EvalError() constructor
=======================
The `EvalError()` constructor creates a new [`EvalError`](../evalerror) instance.
Syntax
------
```
new EvalError()
new EvalError(message)
new EvalError(message, options)
new EvalError(message, fileName)
new EvalError(message, fileName, lineNumber)
EvalError()
EvalError(message)
EvalError(message, options)
EvalError(message, fileName)
EvalError(message, fileName, lineNumber)
```
**Note:** `EvalError()` can be called with or without [`new`](../../operators/new). Both create a new `EvalError` 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
--------
`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-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 |
| `EvalError` | 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)
* [`eval()`](../eval)
javascript Set.prototype.size Set.prototype.size
==================
The `size` accessor property returns the number of (unique) elements in a [`Set`](../set) object.
Try it
------
Description
-----------
The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property.
Examples
--------
### Using size
```
const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add("some text");
console.log(mySet.size); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-set.prototype.size](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-get-set.prototype.size) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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 |
See also
--------
* [`Set`](../set)
javascript Set.prototype.has() Set.prototype.has()
===================
The `has()` method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not.
Try it
------
Syntax
------
```
has(value)
```
### Parameters
`value` The value to test for presence in the `Set` object.
### Return value
Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`.
Examples
--------
### Using the has() method
```
const mySet = new Set();
mySet.add("foo");
console.log(mySet.has("foo")); // true
console.log(mySet.has("bar")); // false
const set1 = new Set();
const obj1 = { key1: 1 };
set1.add(obj1);
console.log(set1.has(obj1)); // true
console.log(set1.has({ key1: 1 })); // false, because they are different object references
console.log(set1.add({ key1: 1 })); // now set1 contains 2 entries
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.has](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`Set`](../set)
* [`Set.prototype.add()`](add)
* [`Set.prototype.delete()`](delete)
javascript Set.prototype.values() Set.prototype.values()
======================
The `values()` method returns a new [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order.
**Note:** The `keys()` method is an alias for this method (for similarity with [`Map`](../map) objects), hence the `keys()` page redirecting here. It behaves exactly the same and returns **values** of `Set` elements.
Try it
------
Syntax
------
```
values()
```
### Return value
A new iterator object containing the values for each element in the given `Set`, in insertion order.
Examples
--------
### Using values()
```
const mySet = new Set();
mySet.add("foo");
mySet.add("bar");
mySet.add("baz");
const setIter = mySet.values();
console.log(setIter.next().value); // "foo"
console.log(setIter.next().value); // "bar"
console.log(setIter.next().value); // "baz"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.values](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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
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
--------
* [`Set.prototype.entries()`](entries)
* [`Set.prototype.keys()`](keys)
javascript Set.prototype.add() Set.prototype.add()
===================
The `add()` method 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`.
Try it
------
Syntax
------
```
add(value)
```
### Parameters
`value` The value of the element to add to the `Set` object.
### Return value
The `Set` object with added value.
Examples
--------
### Using the add() method
```
const mySet = new Set();
mySet.add(1);
mySet.add(5).add("some text"); // chainable
console.log(mySet);
// Set [1, 5, "some text"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.add](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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` | 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 |
See also
--------
* [`Set`](../set)
* [`Set.prototype.delete()`](delete)
* [`Set.prototype.has()`](has)
javascript Set.prototype.keys() Set.prototype.keys()
====================
The `keys()` method is an alias for the [`values()`](values) method.
Syntax
------
```
keys()
```
### Return value
A new iterator object containing the values for each element in the given `Set`, in insertion order.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.values](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.values) |
| [ECMAScript Language Specification # sec-set.prototype.keys](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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
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
--------
* [`Set.prototype.entries()`](entries)
* [`Set.prototype.values()`](values)
javascript Set.prototype[@@iterator]() Set.prototype[@@iterator]()
===========================
The `@@iterator` method of a `Set` object implements the [iterable protocol](../../iteration_protocols) and allows sets 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 values of the set.
The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](values) property.
Try it
------
Syntax
------
```
set[Symbol.iterator]()
```
### Return value
The same return value as [`Set.prototype.values()`](values): a new iterable iterator object that yields the values of the set.
Examples
--------
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `Set` 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 mySet = new Set();
mySet.add("0");
mySet.add(1);
mySet.add({});
for (const v of mySet) {
console.log(v);
}
```
### 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 mySet = new Set();
mySet.add("0");
mySet.add(1);
mySet.add({});
const setIter = mySet[Symbol.iterator]();
console.log(setIter.next().value); // "0"
console.log(setIter.next().value); // 1
console.log(setIter.next().value); // Object
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype-@@iterator](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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` | 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 |
See also
--------
* [`Set.prototype.entries()`](entries)
* [`Set.prototype.keys()`](keys)
* [`Set.prototype.values()`](values)
javascript Set.prototype.clear() Set.prototype.clear()
=====================
The `clear()` method removes all elements from a `Set` object.
Try it
------
Syntax
------
```
clear()
```
### Return value
[`undefined`](../undefined).
Examples
--------
### Using the clear() method
```
const mySet = new Set();
mySet.add(1);
mySet.add("foo");
console.log(mySet.size); // 2
console.log(mySet.has("foo")); // true
mySet.clear();
console.log(mySet.size); // 0
console.log(mySet.has("bar")); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.clear](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.clear) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `clear` | 38 | 12 | 19 | 11 | 25 | 8 | 38 | 38 | 19 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Set`](../set)
* [`Set.prototype.delete()`](delete)
javascript Set.prototype.entries() Set.prototype.entries()
=======================
The `entries()` method returns a new [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains `[value, value]` for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each *entry* has the same value for its *key* and *value* here, so that an array `[value, value]` is returned.
Try it
------
Syntax
------
```
entries()
```
### Return value
A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order.
Examples
--------
### Using entries()
```
const mySet = new Set();
mySet.add("foobar");
mySet.add(1);
mySet.add("baz");
const setIter = mySet.entries();
console.log(setIter.next().value); // ["foobar", "foobar"]
console.log(setIter.next().value); // [1, 1]
console.log(setIter.next().value); // ["baz", "baz"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.entries](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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 | 24 | No | 25 | 8 | 38 | 38 | 24 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Set.prototype.keys()`](keys)
* [`Set.prototype.values()`](values)
| programming_docs |
javascript get Set[@@species] get Set[@@species]
==================
The `Set[@@species]` accessor property is an unused accessor property specifying how to copy `Set` objects.
Syntax
------
```
Set[Symbol.species]
```
### Return value
The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `Set` instances.
Description
-----------
The `@@species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment.
**Note:** This property is currently unused by all `Set` methods.
Examples
--------
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is the `Set` constructor for `Set`.
```
Set[Symbol.species]; // function Set()
```
### Species in derived objects
In an instance of a custom `Set` subclass, such as `MySet`, the `MySet` species is the `MySet` constructor. However, you might want to overwrite this, in order to return parent `Set` objects in your derived class methods:
```
class MySet extends Set {
// Overwrite MySet species to the parent Set constructor
static get [Symbol.species]() {
return Set;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-set-@@species](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-get-set-@@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 | 41 | No | 38 | 10 | 51 | 51 | 41 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* [`Set`](../set)
* [`Symbol.species`](../symbol/species)
javascript Set() constructor Set() constructor
=================
The `Set` lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) or object references.
Try it
------
Syntax
------
```
new Set()
new Set(iterable)
```
**Note:** `Set()` 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 `Set`.
If you don't specify this parameter, or its value is `null`, the new `Set` is empty.
### Return value
A new `Set` object.
Examples
--------
### Using the `Set` object
```
const mySet = new Set();
mySet.add(1); // Set [ 1 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add("some text"); // Set [ 1, 5, 'some text' ]
const o = { a: 1, b: 2 };
mySet.add(o);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set-constructor](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set-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 |
| `Set` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `iterable_allowed` | 38 | 12 | 13 | No | 25 | 9 | 38 | 38 | 14 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `new_required` | 38 | 12 | 42 | 11 | 25 | 9 | 38 | 38 | 42 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `null_allowed` | 38 | 12 | 37 | 11 | 25 | 9 | 38 | 38 | 37 | 25 | 9 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [Polyfill of `Set` in `core-js`](https://github.com/zloirock/core-js#set)
* [`Set`](../set)
javascript Set.prototype.delete() Set.prototype.delete()
======================
The `delete()` method removes a specified value from a `Set` object, if it is in the set.
Try it
------
Syntax
------
```
delete(value)
```
### Parameters
`value` The value to remove from `Set`.
### Return value
Returns `true` if `value` was already in `Set`; otherwise `false`.
Examples
--------
### Using the delete() method
```
const mySet = new Set();
mySet.add("foo");
console.log(mySet.delete("bar")); // false; no "bar" element found to be deleted.
console.log(mySet.delete("foo")); // true; successfully removed.
console.log(mySet.has("foo")); // false; the "foo" element is no longer present.
```
### Deleting an object from a set
Because objects are compared by reference, you have to delete them by checking individual properties if you don't have a reference to the original object.
```
const setObj = new Set(); // Create a new set.
setObj.add({ x: 10, y: 20 }); // Add object in the set.
setObj.add({ x: 20, y: 30 }); // Add object in the set.
// Delete any point with `x > 10`.
setObj.forEach((point) => {
if (point.x > 10) {
setObj.delete(point);
}
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.delete](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`Set`](../set)
* [`Set.prototype.clear()`](clear)
javascript Set.prototype.forEach() Set.prototype.forEach()
=======================
The `forEach()` method executes a provided function once for each value in the `Set` object, in insertion order.
Try it
------
Syntax
------
```
// Arrow function
forEach(() => { /\* ... \*/ } )
forEach((value) => { /\* ... \*/ } )
forEach((value, key) => { /\* ... \*/ } )
forEach((value, key, set) => { /\* ... \*/ } )
// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)
// Inline callback function
forEach(function() { /\* ... \*/ })
forEach(function(value) { /\* ... \*/ })
forEach(function(value, key) { /\* ... \*/ })
forEach(function(value, key, set) { /\* ... \*/ })
forEach(function(value, key, set) { /\* ... \*/ }, thisArg)
```
### Parameters
`callback` Function to execute for each element, taking three arguments:
`value`, `key`
The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments.
`set` The `Set` object which `forEach()` was called upon.
`thisArg` Value to use as `this` when executing `callbackFn`.
### Return value
[`undefined`](../undefined).
Description
-----------
The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`.
`callback` is invoked with **three arguments**:
* the **element value**
* the **element key**
* the `Set`
There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [`Set`](../set). This is to make it consistent with other `forEach()` methods for [`Map`](../map/foreach) and [`Array`](../array/foreach).
If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](../../operators/this).
Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited.
`forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value.
Examples
--------
### Logging the contents of a Set object
The following code logs a line for each element in a `Set` object:
```
function logSetElements(value1, value2, set) {
console.log(`s[${value1}] = ${value2}`);
}
new Set(["foo", "bar", undefined]).forEach(logSetElements);
// Logs:
// "s[foo] = foo"
// "s[bar] = bar"
// "s[undefined] = undefined"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set.prototype.foreach](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.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` | 38 | 12 | 25 | 11 | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Array.prototype.forEach()`](../array/foreach)
* [`Map.prototype.forEach()`](../map/foreach)
javascript InternalError() constructor InternalError() constructor
===========================
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The `InternalError()` constructor creates an error that indicates an error that occurred internally in the JavaScript engine.
Syntax
------
```
new InternalError()
new InternalError(message)
new InternalError(message, options)
new InternalError(message, fileName)
new InternalError(message, fileName, lineNumber)
InternalError()
InternalError(message)
InternalError(message, options)
InternalError(message, fileName)
InternalError(message, fileName, lineNumber)
```
**Note:** `InternalError()` can be called with or without [`new`](../../operators/new). Both create a new `InternalError` 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
--------
### Creating a new InternalError
```
new InternalError("Engine failure");
```
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 |
See also
--------
* [`Error`](../error)
javascript Error.prototype.message Error.prototype.message
=======================
The `message` data property of an [`Error`](../error) instance is a human-readable description of the error.
Value
-----
A string corresponding to the value passed to the [`Error()`](error) constructor as the first argument.
| Property attributes of `Error.prototype.message` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Description
-----------
This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](name) property is used by the [`Error.prototype.toString()`](tostring) method to create a string representation of the Error.
By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](error) constructor.
Examples
--------
### Throwing a custom error
```
const e = new Error("Could not parse input");
// e.message is 'Could not parse input'
throw e;
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-error.prototype.message](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-error.prototype.message) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `message` | 1 | 12 | 1 | 6 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Error.prototype.name`](name)
* [`Error.prototype.toString()`](tostring)
javascript Error.prototype.lineNumber Error.prototype.lineNumber
==========================
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The `lineNumber` data property of an [`Error`](../error) instance contains the line number in the file that raised this error.
Value
-----
A positive integer.
| Property attributes of `Error.prototype.lineNumber` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Examples
--------
### Using lineNumber
```
try {
throw new Error("Could not parse input");
} catch (err) {
console.log(err.lineNumber); // 2
}
```
### Alternative example using error event
```
window.addEventListener("error", (e) => {
console.log(e.lineNumber); // 5
});
const e = new Error("Could not parse input");
throw e;
```
This is not a standard feature and lacks widespread support. See the browser compatibility table below.
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 |
| `lineNumber` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
See also
--------
* [`Error.prototype.stack`](stack)
* [`Error.prototype.columnNumber`](columnnumber)
* [`Error.prototype.fileName`](filename)
javascript Error.prototype.cause Error.prototype.cause
=====================
The `cause` data property of an [`Error`](../error) instance indicates the specific original cause of the error.
It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error.
Value
-----
The value that was passed to the [`Error()`](error) constructor in the `options.cause` argument. It may not be present.
| Property attributes of `Error.prototype.cause` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Description
-----------
The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause.
Examples
--------
### Rethrowing an error with a cause
It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new `Error`, as shown.
```
try {
connectToDatabase();
} catch (err) {
throw new Error('Connecting to database failed.', { cause: err });
}
```
For a more detailed example see [Error > Differentiate between similar errors](../error#differentiate_between_similar_errors).
### Providing structured data as the error cause
Error messages written for human consumption may be inappropriate for machine parsing β since they're subject to rewording or punctuation changes that may break any existing parsing written to consume them. So when throwing an error from a function, as an alternative to a human-readable error message, you can instead provide the cause as structured data, for machine parsing.
```
function makeRSA(p, q) {
if (!Number.isInteger(p) || !Number.isInteger(q)) {
throw new Error('RSA key generation requires integer inputs.', {
cause: { code: 'NonInteger', values: [p, q] },
});
}
if (!areCoprime(p, q)) {
throw new Error('RSA key generation requires two co-prime integers.', {
cause: { code: 'NonCoprime', values: [p, q] },
})
}
// rsa algorithmβ¦
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-installerrorcause](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-installerrorcause) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `cause` | 93 | 93 | 91 | No | No | 15 | 93 | 93 | 91 | No | 15 | 17.0 | 1.13 | 16.9.0 |
See also
--------
* [`Error.prototype.message`](message)
* [`Error.prototype.toString()`](tostring)
javascript Error.prototype.name Error.prototype.name
====================
The `name` data property of `Error.prototype` is shared by all [`Error`](../error) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../typeerror) and [`SyntaxError`](../syntaxerror) provide their own `name` properties.
Value
-----
A string. For `Error.prototype.name`, the initial value is `"Error"`.
| Property attributes of `Error.prototype.name` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Description
-----------
By default, [`Error`](../error) instances are given the name "Error". The `name` property, in addition to the [`message`](message) property, is used by the [`Error.prototype.toString()`](tostring) method to create a string representation of the error.
Examples
--------
### Throwing a custom error
```
const e = new Error("Malformed input"); // e.name is 'Error'
e.name = "ParseError";
throw e;
// e.toString() would return 'ParseError: Malformed input'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-error.prototype.name](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-error.prototype.name) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Error.prototype.message`](message)
* [`Error.prototype.toString()`](tostring)
| programming_docs |
javascript Error.prototype.columnNumber Error.prototype.columnNumber
============================
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The `columnNumber` data property of an [`Error`](../error) instance contains the column number in the line of the file that raised this error.
Value
-----
A positive integer.
| Property attributes of `Error.prototype.columnNumber` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Examples
--------
### Using columnNumber
```
try {
throw new Error("Could not parse input");
} catch (err) {
console.log(err.columnNumber); // 9
}
```
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 |
| `columnNumber` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
See also
--------
* [`Error.prototype.stack`](stack)
* [`Error.prototype.lineNumber`](linenumber)
* [`Error.prototype.fileName`](filename)
javascript Error.prototype.toString() Error.prototype.toString()
==========================
The `toString()` method returns a string representing the specified [`Error`](../error) object.
Syntax
------
```
toString()
```
### Return value
A string representing the specified [`Error`](../error) object.
Description
-----------
The [`Error`](../error) object overrides the [`Object.prototype.toString()`](../object/tostring) method inherited by all objects. Its semantics are as follows (assuming [`Object`](../object) and [`String`](../string) have their original values):
```
Error.prototype.toString = function () {
if (
this === null ||
(typeof this !== "object" && typeof this !== "function")
) {
throw new TypeError();
}
let name = this.name;
name = name === undefined ? "Error" : `${name}`;
let msg = this.message;
msg = msg === undefined ? "" : `${name}`;
if (name === "") {
return msg;
}
if (msg === "") {
return name;
}
return `${name}: ${msg}`;
};
```
Examples
--------
### Using toString()
```
const e1 = new Error("fatal error");
console.log(e1.toString()); // "Error: fatal error"
const e2 = new Error("fatal error");
e2.name = undefined;
console.log(e2.toString()); // "Error: fatal error"
const e3 = new Error("fatal error");
e3.name = '';
console.log(e3.toString()); // "fatal error"
const e4 = new Error("fatal error");
e4.name = "";
e4.message = undefined;
console.log(e4.toString()); // ""
const e5 = new Error("fatal error");
e5.name = "hello";
e5.message = undefined;
console.log(e5.toString()); // "hello"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-error.prototype.tostring](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-error.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 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [A polyfill of `Error.prototype.toString`](https://github.com/zloirock/core-js#ecmascript-error) with many bug fixes is available in [`core-js`](https://github.com/zloirock/core-js)
javascript Error() constructor Error() constructor
===================
The `Error()` constructor creates an error object.
Syntax
------
```
new Error()
new Error(message)
new Error(message, options)
new Error(message, fileName)
new Error(message, fileName, lineNumber)
Error()
Error(message)
Error(message, options)
Error(message, fileName)
Error(message, fileName, lineNumber)
```
**Note:** `Error()` can be called with or without [`new`](../../operators/new). Both create a new `Error` instance.
### Parameters
`message` Optional
A human-readable description of the error.
`options` Optional
An object that has the following properties:
`cause` Optional
A value indicating the specific cause of the error, reflected in the [`cause`](cause) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
`fileName` Optional Non-standard
The path to the file that raised this error, reflected in the [`fileName`](filename) property. Defaults to the name of the file containing the code that called the `Error()` constructor.
`lineNumber` Optional Non-standard
The line number within the file on which the error was raised, reflected in the [`lineNumber`](linenumber) property. Defaults to the line number containing the `Error()` constructor invocation.
Examples
--------
### Function call or new construction
When `Error` is used like a function, that is without [`new`](../../operators/new), it will return an `Error` object. Therefore, a mere call to `Error` will produce the same output that constructing an `Error` object via the `new` keyword would.
```
const x = Error("I was created using a function call!");
// above has the same functionality as following
const y = new Error('I was constructed via the "new" keyword!');
```
### Rethrowing an error with a cause
It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new `Error`, as shown.
```
try {
frameworkThatCanThrow();
} catch (err) {
throw new Error("New error message", { cause: err });
}
```
For a more detailed example see [Error > Differentiate between similar errors](../error#differentiate_between_similar_errors).
### Omitting options argument
JavaScript only tries to read `options.cause` if `options` is an object β this avoids ambiguity with the other non-standard `Error(message, fileName, lineNumber)` signature, which requires the second parameter to be a string. If you omit `options`, pass a primitive value as `options`, or pass an object without the `cause` property, then the created `Error` object will have no `cause` property.
```
// Omitting options
const error1 = new Error("Error message");
console.log("cause" in error1); // false
// Passing a primitive value
const error2 = new Error("Error message", "");
console.log("cause" in error2); // false
// Passing an object without a cause property
const error3 = new Error("Error message", { details: "http error" });
console.log("cause" in error3); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-error-constructor](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-error-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 |
| `Error` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `fileName_parameter` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
| `lineNumber_parameter` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
| `options_cause_parameter` | 93 | 93 | 91 | No | 79 | 15 | 93 | 93 | 91 | No | 15 | 17.0 | 1.13 | 16.9.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)
* [Error causes](https://v8.dev/features/error-cause) (v8.dev/features)
javascript Error.prototype.fileName Error.prototype.fileName
========================
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The `fileName` data property of an [`Error`](../error) instance contains the path to the file that raised this error.
Value
-----
A string.
| Property attributes of `Error.prototype.fileName` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Description
-----------
This non-standard property contains the path to the file that raised this error. If called from a debugger context, the Firefox Developer Tools for example, "debugger eval code" is returned.
Examples
--------
### Using fileName
```
const e = new Error("Could not parse input");
throw e;
// e.fileName could look like "file:///C:/example.html"
```
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 |
| `fileName` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
See also
--------
* [`Error.prototype.stack`](stack)
* [`Error.prototype.columnNumber`](columnnumber)
* [`Error.prototype.lineNumber`](linenumber)
javascript Error.prototype.stack Error.prototype.stack
=====================
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The non-standard `stack` property of an [`Error`](../error) instance offers a trace of which functions were called, in what order, from which line and file, and with what arguments. The stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call.
Value
-----
A string.
Because the `stack` property is non-standard, implementations differ about where it's installed.
* In Firefox, it's an accessor property on `Error.prototype`.
* In Chrome and Safari, it's a data property on each `Error` instance, with the descriptor:
| Property attributes of `Error.prototype.stack` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Description
-----------
Each step will be separated by a newline, with the first part of the line being the function name (if not a call from the global scope), then by an at (@) sign, the file location (except when the function is the error constructor as the error is being thrown), a colon, and, if there is a file location, the line number. (Note that the [`Error`](../error) object also possesses the `fileName`, `lineNumber` and `columnNumber` properties for retrieving these from the error thrown (but only the error, and not its trace).)
Note that this is the format used by Firefox. There is no standard formatting. However, Safari 6+ and Opera 12- use a very similar format. Browsers using the V8 JavaScript engine (such as Chrome, Opera 15+, Android Browser) and IE10+, on the other hand, uses a different format.
**Argument values in the stack**: Prior to Firefox 14, the function name would be followed by the argument values converted to string in parentheses immediately before the at (`@`) sign. While an object (or array, etc.) would appear in the converted form `"[object Object]"`, and as such could not be evaluated back into the actual objects, scalar values could be retrieved (though it may be β it is still possible in Firefox 14 β easier to use `arguments.callee.caller.arguments`, as could the function name be retrieved by `arguments.callee.caller.name`). `"undefined"` is listed as `"(void 0)"`. Note that if string arguments were passed in with values such as `"@"`, `"("`, `")"` (or if in file names), you could not easily rely on these for breaking the line into its component parts. Thus, in Firefox 14 and later this is less of an issue.
Different browsers set this value at different times. For example, Firefox sets it when creating an [`Error`](../error) object, while PhantomJS sets it only when throwing the [`Error`](../error), and [archived MSDN docs](https://web.archive.org/web/20180618201428/https://docs.microsoft.com/scripting/javascript/reference/stack-property-error-javascript) also seem to match the PhantomJS implementation.
Examples
--------
### Using the stack property
The following HTML markup demonstrates the use of `stack` property.
```
<!DOCTYPE html>
<meta charset="UTF-8" />
<title>Stack Trace Example</title>
<body>
<script>
function trace() {
try {
throw new Error("myError");
} catch (e) {
alert(e.stack);
}
}
function b() {
trace();
}
function a() {
b(3, 4, "\n\n", undefined, {});
}
a("first call, firstarg");
</script>
</body>
```
Assuming the above markup is saved as `C:\example.html` on a Windows file system it produces an alert message box with the following text:
Starting with Firefox 30 and later containing the column number:
```
trace@file:///C:/example.html:9:17
b@file:///C:/example.html:16:13
a@file:///C:/example.html:19:13
@file:///C:/example.html:21:9
```
Firefox 14 to Firefox 29:
```
trace@file:///C:/example.html:9
b@file:///C:/example.html:16
a@file:///C:/example.html:19
@file:///C:/example.html:21
```
Firefox 13 and earlier would instead produce the following text:
```
Error("myError")@:0
trace()@file:///C:/example.html:9
b(3,4,"\n\n",(void 0),[object Object])@file:///C:/example.html:16
a("first call, firstarg")@file:///C:/example.html:19
@file:///C:/example.html:21
```
### Stack of eval'ed code
Starting with Firefox 30, the error stack of code in `Function()` and `eval()` calls, now produces stacks with more detailed information about the line and column numbers inside these calls. Function calls are indicated with `"> Function"` and eval calls with `"> eval"`.
```
try {
new Function("throw new Error()")();
} catch (e) {
console.log(e.stack);
}
// anonymous@file:///C:/example.html line 7 > Function:1:1
// @file:///C:/example.html:7:6
try {
eval("eval('FAIL')");
} catch (x) {
console.log(x.stack);
}
// @file:///C:/example.html line 7 > eval line 1 > eval:1:1
// @file:///C:/example.html line 7 > eval:1:1
// @file:///C:/example.html:7:6
```
You can also use the `//# sourceURL` directive to name an eval source. See also [Debug eval sources](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/debug_eval_sources/index.html) in the [Debugger](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html) docs and this [blog post](https://fitzgeraldnick.com/2014/12/05/name-eval-scripts.html).
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 |
| `Stack` | 3 | 12 | 1 | 10 | 10.5 | 6 | β€37 | 18 | 4 | 11 | 6 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* External projects: [TraceKit](https://github.com/csnover/TraceKit/) and [javascript-stacktrace](https://github.com/stacktracejs/stacktrace.js)
* [Overview of the V8 JavaScript stack trace API](https://v8.dev/docs/stack-trace-api)
javascript FinalizationRegistry.prototype.register() FinalizationRegistry.prototype.register()
=========================================
The `register()` method registers an object with a [`FinalizationRegistry`](../finalizationregistry) instance so that if the object is garbage-collected, the registry's callback may get called.
Syntax
------
```
register(target, heldValue)
register(target, heldValue, unregisterToken)
```
### Parameters
`target` The target object to register.
`heldValue` The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives.
`unregisterToken` Optional
A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered.
### Return value
`undefined`.
### Exceptions
[`TypeError`](../typeerror) Thrown when one of the following condition is met:
* `target` is not an object (object as opposed to primitives; functions are objects as well)
* `target` is the same as `heldvalue` (`target === heldValue`)
* `unregisterToken` is not an object
Description
-----------
See the [Avoid where possible](../finalizationregistry#avoid_where_possible) and [Notes on cleanup callbacks](../finalizationregistry#notes_on_cleanup_callbacks) sections of the [`FinalizationRegistry`](../finalizationregistry) page for important caveats.
Examples
--------
### Using register
The following registers the target object referenced by `target`, passing in the held value `"some value"` and passing the target object itself as the unregistration token:
```
registry.register(target, "some value", target);
```
The following registers the target object referenced by `target`, passing in another object as the held value, and not passing in any unregistration token (which means `target` can't be unregistered):
```
registry.register(target, { useful: "info about target" });
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-finalization-registry.prototype.register](https://tc39.es/ecma262/multipage/managing-memory.html#sec-finalization-registry.prototype.register) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `register` | 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)
javascript FinalizationRegistry() constructor FinalizationRegistry() constructor
==================================
The `FinalizationRegistry` constructor creates a [`FinalizationRegistry`](../finalizationregistry) object that uses the given callback.
Syntax
------
```
// Arrow callback function
new FinalizationRegistry((heldValue) => { /\* β¦ \*/ })
// Callback function
new FinalizationRegistry(callbackFn)
// Inline callback function
new FinalizationRegistry(function(heldValue) { /\* β¦ \*/ })
```
**Note:** `FinalizationRegistry()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`callback` The callback function this registry should use.
Examples
--------
### Creating a new registry
You create the registry passing in the callback:
```
const registry = new FinalizationRegistry((heldValue) => {
// β¦
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-finalization-registry-constructor](https://tc39.es/ecma262/multipage/managing-memory.html#sec-finalization-registry-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 |
| `FinalizationRegistry` | 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)
| programming_docs |
javascript FinalizationRegistry.prototype.unregister() FinalizationRegistry.prototype.unregister()
===========================================
The `unregister()` method unregisters a target object from a [`FinalizationRegistry`](../finalizationregistry) instance.
Syntax
------
```
unregister(unregisterToken)
```
### Parameters
`unregisterToken` The token used with the [`register`](register) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together.
### Return value
A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered.
### Exceptions
[`TypeError`](../typeerror) Thrown when `unregisterToken` is not an object.
Description
-----------
When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one.
Examples
--------
### Using unregister
This example shows registering a target object using that same object as the unregister token, then later unregistering it via `unregister`:
```
class Thingy {
static #cleanup = (label) => {
// ^^^^^βββββ held value
console.error(
`The "release" method was never called for the object with the label "${label}"`
);
};
#registry = new FinalizationRegistry(Thingy.#cleanup);
/\*\*
\* Constructs a `Thingy` instance.
\* Be sure to call `release` when you're done with it.
\*
\* @param label A label for the `Thingy`.
\*/
constructor(label) {
// vvvvvβββββ held value
this.#registry.register(this, label, this);
// target βββββ^^^^ ^^^^βββββ unregister token
}
/\*\*
\* Releases resources held by this `Thingy` instance.
\*/
release() {
this.#registry.unregister(this);
// ^^^^βββββ unregister token
}
}
```
This example shows registering a target object using a different object as its unregister token:
```
class Thingy {
static #cleanup = (file) => {
// ^^^^βββββ held value
console.error(
`The "release" method was never called for the "Thingy" for the file "${file.name}"`
);
};
#registry = new FinalizationRegistry(Thingy.#cleanup);
#file;
/\*\*
\* Constructs a `Thingy` instance for the given file.
\* Be sure to call `release` when you're done with it.
\*
\* @param filename The name of the file.
\*/
constructor(filename) {
this.#file = File.open(filename);
// vvvvvβββββ held value
this.#registry.register(this, label, this.#file);
// target βββββ^^^^ ^^^^^^^^^^βββββ unregister token
}
/\*\*
\* Releases resources held by this `Thingy` instance.
\*/
release() {
if (this.#file) {
this.#registry.unregister(this.#file);
// ^^^^^^^^^^βββββ unregister token
File.close(this.#file);
this.#file = null;
}
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-finalization-registry.prototype.unregister](https://tc39.es/ecma262/multipage/managing-memory.html#sec-finalization-registry.prototype.unregister) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `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
--------
* [`FinalizationRegistry`](../finalizationregistry)
javascript BigInt64Array() constructor BigInt64Array() constructor
===========================
The `BigInt64Array()` typed array constructor creates a new [`BigInt64Array`](../bigint64array) object, which is, 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).
Syntax
------
```
new BigInt64Array()
new BigInt64Array(length)
new BigInt64Array(typedArray)
new BigInt64Array(object)
new BigInt64Array(buffer)
new BigInt64Array(buffer, byteOffset)
new BigInt64Array(buffer, byteOffset, length)
```
**Note:** `BigInt64Array()` 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 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-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 |
| `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 SyntaxError() constructor SyntaxError() constructor
=========================
The `SyntaxError` constructor creates a new error object that represents an error when trying to interpret syntactically invalid code.
Syntax
------
```
new SyntaxError()
new SyntaxError(message)
new SyntaxError(message, options)
new SyntaxError(message, fileName)
new SyntaxError(message, fileName, lineNumber)
SyntaxError()
SyntaxError(message)
SyntaxError(message, options)
SyntaxError(message, fileName)
SyntaxError(message, fileName, lineNumber)
```
**Note:** `SyntaxError()` can be called with or without [`new`](../../operators/new). Both create a new `SyntaxError` 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 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-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 |
| `SyntaxError` | 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)
javascript Int16Array() constructor Int16Array() constructor
========================
The `Int16Array()` typed array constructor creates 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).
Syntax
------
```
new Int16Array()
new Int16Array(length)
new Int16Array(typedArray)
new Int16Array(object)
new Int16Array(buffer)
new Int16Array(buffer, byteOffset)
new Int16Array(buffer, byteOffset, length)
```
**Note:** `Int16Array()` 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 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 # 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 |
| `Int16Array` | 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 `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 Int8Array() constructor Int8Array() constructor
=======================
The `Int8Array()` constructor creates a typed 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).
Syntax
------
```
new Int8Array()
new Int8Array(length)
new Int8Array(typedArray)
new Int8Array(object)
new Int8Array(buffer)
new Int8Array(buffer, byteOffset)
new Int8Array(buffer, byteOffset, length)
```
**Note:** `Int8Array()` 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 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 # 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 |
| `Int8Array` | 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 `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 Rest parameters Rest parameters
===============
The **rest parameter** syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent [variadic functions](https://en.wikipedia.org/wiki/Variadic_function) in JavaScript.
Try it
------
Syntax
------
```
function f(a, b, ...theArgs) {
// β¦
}
```
Description
-----------
A function definition's last parameter can be prefixed with `...` (three U+002E FULL STOP characters), which will cause all remaining (user supplied) parameters to be placed within an [`Array`](../global_objects/array) object.
```
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]
```
A function definition can only have one rest parameter, and the rest parameter must be the last parameter in the function definition.
```
function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}
```
The rest parameter is not counted towards the function's [`length`](../global_objects/function/length) property.
### The difference between rest parameters and the arguments object
There are three main differences between rest parameters and the [`arguments`](arguments) object:
* The `arguments` object is **not a real array**, while rest parameters are [`Array`](../global_objects/array) instances, meaning methods like [`sort()`](../global_objects/array/sort), [`map()`](../global_objects/array/map), [`forEach()`](../global_objects/array/foreach) or [`pop()`](../global_objects/array/pop) can be applied on it directly.
* The `arguments` object has the additional (deprecated) [`callee`](arguments/callee) property.
* In a non-strict function with simple parameters, the `arguments` object [syncs its indices with the values of parameters](arguments#assigning_to_indices). The rest parameter array never updates its value when the named parameters are re-assigned.
* The rest parameter bundles all the *extra* parameters into a single array, but does not contain any named argument defined *before* the `...restParam`. The `arguments` object contains all of the parameters β including the parameters in the `...restParam` array β bundled into one array-like object.
Examples
--------
### Using rest parameters
In this example, the first argument is mapped to `a` and the second to `b`, so these named arguments are used as normal.
However, the third argument, `manyMoreArgs`, will be an array that contains the third, fourth, fifth, sixth, β¦, nth β as many arguments as the user specifies.
```
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five", "six"] <-- an array
```
Below, even though there is just one value, the last argument still gets put into an array.
```
// Using the same function definition from example above
myFun("one", "two", "three");
// a, "one"
// b, "two"
// manyMoreArgs, ["three"] <-- an array with just one value
```
Below, the third argument isn't provided, but `manyMoreArgs` is still an array (albeit an empty one).
```
// Using the same function definition from example above
myFun("one", "two");
// a, "one"
// b, "two"
// manyMoreArgs, [] <-- still an array
```
Below, only one argument is provided, so `b` gets the default value `undefined`, but `manyMoreArgs` is still an empty array.
```
// Using the same function definition from example above
myFun("one");
// a, "one"
// b, undefined
// manyMoreArgs, [] <-- still an array
```
### Argument length
Since `theArgs` is an array, a count of its elements is given by the [`length`](../global_objects/array/length) property. If the function's only parameter is a rest parameter, `restParams.length` will be equal to [`arguments.length`](arguments/length).
```
function fun1(...theArgs) {
console.log(theArgs.length);
}
fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3
```
### Using rest parameters in combination with ordinary parameters
In the next example, a rest parameter is used to collect all parameters after the first parameter into an array. Each one of the parameter values collected into the array is then multiplied by the first parameter, and the array is returned:
```
function multiply(multiplier, ...theArgs) {
return theArgs.map((element) => multiplier \* element);
}
const arr = multiply(2, 15, 25, 42);
console.log(arr); // [30, 50, 84]
```
### From arguments to an array
[`Array`](../global_objects/array) methods can be used on rest parameters, but not on the `arguments` object:
```
function sortRestArgs(...theArgs) {
const sortedArgs = theArgs.sort();
return sortedArgs;
}
console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7
function sortArguments() {
const sortedArgs = arguments.sort();
return sortedArgs; // this will never happen
}
console.log(sortArguments(5, 3, 7, 1));
// throws a TypeError (arguments.sort is not a function)
```
Rest parameters were introduced to reduce the boilerplate code that was commonly used for converting a set of arguments to an array.
Before rest parameters, `arguments` need to be converted to a normal array before calling array methods on them:
```
function fn(a, b) {
const normalArray = Array.prototype.slice.call(arguments);
// β or β
const normalArray2 = [].slice.call(arguments);
// β or β
const normalArrayFrom = Array.from(arguments);
const first = normalArray.shift(); // OK, gives the first argument
const firstBad = arguments.shift(); // ERROR (arguments is not a normal array)
}
```
Now, you can easily gain access to a normal array using a rest parameter:
```
function fn(...args) {
const normalArray = args;
const first = normalArray.shift(); // OK, gives the first argument
}
```
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 |
| `rest_parameters` | 47 | 12 | 15 | No | 34 | 10 | 47 | 47 | 15 | 34 | 10 | 5.0 | 1.0 | 6.0.0
4.0.0 |
| `destructuring` | 49 | 79 | 52 | No | 36 | 10 | 49 | 49 | 52 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Spread syntax](../operators/spread_syntax) (also '`...`')
* [Destructuring assignment](../operators/destructuring_assignment)
* [`arguments` object](arguments)
* [`Array`](../global_objects/array)
| programming_docs |
javascript Arrow function expressions Arrow function expressions
==========================
An **arrow function expression** is a compact alternative to a traditional [function expression](../operators/function), with some semantic differences and deliberate limitations in usage:
* Arrow functions don't have their own bindings to [`this`](../operators/this), [`arguments`](arguments), or [`super`](../operators/super), and should not be used as [methods](https://developer.mozilla.org/en-US/docs/Glossary/Method).
* Arrow functions cannot be used as [constructors](https://developer.mozilla.org/en-US/docs/Glossary/Constructor). Calling them with [`new`](../operators/new) throws a [`TypeError`](../global_objects/typeerror). They also don't have access to the [`new.target`](../operators/new.target) keyword.
* Arrow functions cannot use [`yield`](../operators/yield) within their body and cannot be created as generator functions.
Try it
------
Syntax
------
```
param => expression
(param) => expression
(param1, paramN) => expression
param => {
statements
}
(param1, paramN) => {
statements
}
```
[Rest parameters](rest_parameters), [default parameters](default_parameters), and [destructuring](../operators/destructuring_assignment) within params are supported, and always require parentheses:
```
(a, b, ...r) => expression
(a = 400, b = 20, c) => expression
([a, b] = [10, 20]) => expression
({ a, b } = { a: 10, b: 20 }) => expression
```
Arrow functions can be [`async`](../statements/async_function) by prefixing the expression with the `async` keyword.
```
async param => expression
async (param1, param2, ...paramN) => {
statements
}
```
Description
-----------
Let's decompose a traditional anonymous function down to the simplest arrow function step-by-step. Each step along the way is a valid arrow function.
**Note:** Traditional function expressions and arrow functions have more differences than their syntax. We will introduce their behavior differences in more detail in the next few subsections.
```
// Traditional anonymous function
(function (a) {
return a + 100;
});
// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
return a + 100;
};
// 2. Remove the body braces and word "return" β the return is implied.
(a) => a + 100;
// 3. Remove the parameter parentheses
a => a + 100;
```
In the example above, both the parentheses around the parameter and the braces around the function body may be omitted. However, they can only be omitted in certain cases.
The parentheses can only be omitted if the function has a single simple parameter. If it has multiple parameters, no parameters, or default, destructured, or rest parameters, the parentheses around the parameter list are required.
```
// Traditional anonymous function
(function (a, b) {
return a + b + 100;
});
// Arrow function
(a, b) => a + b + 100;
const a = 4;
const b = 2;
// Traditional anonymous function (no parameters)
(function() {
return a + b + 100;
});
// Arrow function (no arguments)
() => a + b + 100;
```
The braces can only be omitted if the function directly returns an expression. If the body has additional lines of processing, the braces are required β and so is the `return` keyword. Arrow functions cannot guess what or when you want to return.
```
// Traditional anonymous function
(function (a, b) {
const chuck = 42;
return a + b + chuck;
});
// Arrow function
(a, b) => {
const chuck = 42;
return a + b + chuck;
};
```
Arrow functions are always unnamed. If the arrow function needs to call itself, use a named function expression instead. You can also assign the arrow function to a variable so it has a name.
```
// Traditional Function
function bob(a) {
return a + 100;
}
// Arrow Function
const bob2 = (a) => a + 100;
```
### Function body
Arrow functions can have either a *concise body* or the usual *block body*.
In a concise body, only a single expression is specified, which becomes the implicit return value. In a block body, you must use an explicit `return` statement.
```
const func = (x) => x \* x;
// concise body syntax, implied "return"
const func2 = (x, y) => {
return x + y;
};
// with block body, explicit "return" needed
```
Returning object literals using the concise body syntax `(params) => { object: literal }` does not work as expected.
```
const func = () => { foo: 1 };
// Calling func() returns undefined!
const func2 = () => { foo: function () {} };
// SyntaxError: function statement requires a name
const func3 = () => { foo() {} };
// SyntaxError: Unexpected token '{'
```
This is because JavaScript only sees the arrow function as having a concise body if the token following the arrow is not a left brace, so the code inside braces ({}) is parsed as a sequence of statements, where `foo` is a [label](../statements/label), not a key in an object literal.
To fix this, wrap the object literal in parentheses:
```
const func = () => ({ foo: 1 });
```
### Cannot be used as methods
Arrow function expressions should only be used for non-method functions because they do not have their own `this`. Let's see what happens when we try to use them as methods:
```
"use strict";
const obj = {
i: 10,
b: () => console.log(this.i, this),
c() {
console.log(this.i, this);
},
};
obj.b(); // logs undefined, Window { /\* β¦ \*/ } (or the global object)
obj.c(); // logs 10, Object { /\* β¦ \*/ }
```
Another example involving [`Object.defineProperty()`](../global_objects/object/defineproperty):
```
'use strict';
const obj = {
a: 10,
};
Object.defineProperty(obj, 'b', {
get: () => {
console.log(this.a, typeof this.a, this); // undefined 'undefined' Window { /\* β¦ \*/ } (or the global object)
return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
},
});
```
Because a [class](../classes)'s body has a `this` context, arrow functions as [class fields](../classes/public_class_fields) close over the class's `this` context, and the `this` inside the arrow function's body will correctly point to the instance (or the class itself, for [static fields](../classes/static)). However, because it is a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), not the function's own binding, the value of `this` will not change based on the execution context.
```
class C {
a = 1;
autoBoundMethod = () => {
console.log(this.a);
}
}
const c = new C();
c.autoBoundMethod(); // 1
const { autoBoundMethod } = c;
autoBoundMethod(); // 1
// If it were a normal method, it should be undefined in this case
```
Arrow function properties are often said to be "auto-bound methods", because the equivalent with normal methods is:
```
class C {
a = 1;
constructor() {
this.method = this.method.bind(this);
}
method() {
console.log(this.a);
}
}
```
**Note:** Class fields are defined on the *instance*, not on the *prototype*, so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.
For similar reasons, the [`call()`](../global_objects/function/call), [`apply()`](../global_objects/function/apply), and [`bind()`](../global_objects/function/bind) methods are not useful when called on arrow functions, because arrow functions establish `this` based on the scope the arrow function is defined within, and the `this` value does not change based on how the function is invoked.
### No binding of arguments
Arrow functions do not have their own [`arguments`](arguments) object. Thus, in this example, `arguments` is a reference to the arguments of the enclosing scope:
```
const arguments = [1, 2, 3];
const arr = () => arguments[0];
arr(); // 1
function foo(n) {
const f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
return f();
}
foo(3); // 3 + 3 = 6
```
**Note:** You cannot declare a variable called `arguments` in [strict mode](../strict_mode#making_eval_and_arguments_simpler), so the code above would be a syntax error. This makes the scoping effect of `arguments` much easier to comprehend.
In most cases, using [rest parameters](rest_parameters) is a good alternative to using an `arguments` object.
```
function foo(n) {
const f = (...args) => args[0] + n;
return f(10);
}
foo(1); // 11
```
### Cannot be used as constructors
Arrow functions cannot be used as constructors and will throw an error when called with [`new`](../operators/new). They also do not have a [`prototype`](../global_objects/function/prototype) property.
```
const Foo = () => {};
const foo = new Foo(); // TypeError: Foo is not a constructor
console.log("prototype" in Foo); // false
```
### Cannot be used as generators
The [`yield`](../operators/yield) keyword cannot be used in an arrow function's body (except when used within generator functions further nested within the arrow function). As a consequence, arrow functions cannot be used as generators.
### Line break before arrow
An arrow function cannot contain a line break between its parameters and its arrow.
```
const func = (a, b, c)
=> 1;
// SyntaxError: Unexpected token '=>'
```
For the purpose of formatting, you may put the line break after the arrow or use parentheses/braces around the function body, as shown below. You can also put line breaks between parameters.
```
const func = (a, b, c) =>
1;
const func2 = (a, b, c) => (
1
);
const func3 = (a, b, c) => {
return 1;
};
const func4 = (
a,
b,
c,
) => 1;
```
### Precedence of arrow
Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with [operator precedence](../operators/operator_precedence) compared to regular functions.
```
let callback;
callback = callback || () => {};
// SyntaxError: invalid arrow-function arguments
```
Because `=>` has a lower precedence than most operators, parentheses are necessary to avoid `callback || ()` being parsed as the arguments list of the arrow function.
```
callback = callback || (() => {});
```
Examples
--------
### Using arrow functions
```
// An empty arrow function returns undefined
const empty = () => {};
(() => 'foobar')();
// Returns "foobar"
// (this is an Immediately Invoked Function Expression)
const simple = (a) => a > 15 ? 15 : a;
simple(16); // 15
simple(10); // 10
const max = (a, b) => a > b ? a : b;
// Easy array filtering, mapping, etc.
const arr = [5, 6, 13, 0, 1, 18, 23];
const sum = arr.reduce((a, b) => a + b);
// 66
const even = arr.filter((v) => v % 2 === 0);
// [6, 0, 18]
const double = arr.map((v) => v \* 2);
// [10, 12, 26, 0, 2, 36, 46]
// More concise promise chains
promise
.then((a) => {
// β¦
})
.then((b) => {
// β¦
});
// Parameterless arrow functions that are visually easier to parse
setTimeout(() => {
console.log("I happen sooner");
setTimeout(() => {
// deeper code
console.log("I happen later");
}, 1);
}, 1);
```
### Using call, bind, and apply
The [`call()`](../global_objects/function/call), [`apply()`](../global_objects/function/apply), and [`bind()`](../global_objects/function/bind) methods work as expected with traditional functions, because we establish the scope for each of the methods:
```
const obj = {
num: 100,
};
// Setting "num" on globalThis to show how it is NOT used.
globalThis.num = 42;
// A simple traditional function to operate on "this"
const add = function (a, b, c) {
return this.num + a + b + c;
};
console.log(add.call(obj, 1, 2, 3)); // 106
console.log(add.apply(obj, [1, 2, 3])); // 106
const boundAdd = add.bind(obj);
console.log(boundAdd(1, 2, 3)); // 106
```
With arrow functions, since our `add` function is essentially created on the `globalThis` (global) scope, it will assume `this` is the `globalThis`.
```
const obj = {
num: 100,
};
// Setting "num" on globalThis to show how it gets picked up.
globalThis.num = 42;
// Arrow function
const add = (a, b, c) => this.num + a + b + c;
console.log(add.call(obj, 1, 2, 3)); // 48
console.log(add.apply(obj, [1, 2, 3])); // 48
const boundAdd = add.bind(obj);
console.log(boundAdd(1, 2, 3)); // 48
```
Perhaps the greatest benefit of using arrow functions is with methods like [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) and [`EventTarget.prototype.addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) that usually require some kind of closure, `call()`, `apply()`, or `bind()` to ensure that the function is executed in the proper scope.
With traditional function expressions, code like this does not work as expected:
```
const obj = {
count: 10,
doSomethingLater() {
setTimeout(function () { // the function executes on the window scope
this.count++;
console.log(this.count);
}, 300);
},
};
obj.doSomethingLater(); // logs "NaN", because the property "count" is not in the window scope.
```
With arrow functions, the `this` scope is more easily preserved:
```
const obj = {
count: 10,
doSomethingLater() {
// The method syntax binds "this" to the "obj" context.
setTimeout(() => {
// Since the arrow function doesn't have its own binding and
// setTimeout (as a function call) doesn't create a binding
// itself, the "obj" context of the outer method is used.
this.count++;
console.log(this.count);
}, 300);
},
};
obj.doSomethingLater(); // logs 11
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-arrow-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-arrow-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 |
| `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. |
| `trailing_comma` | 58 | 12 | 52 | No | 45 | 10 | 58 | 58 | 52 | 43 | 10 | 7.0 | 1.0 | 8.0.0 |
See also
--------
* ["ES6 In Depth: Arrow functions" on hacks.mozilla.org](https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/)
javascript Default parameters Default parameters
==================
**Default function parameters** allow named parameters to be initialized with default values if no value or `undefined` is passed.
Try it
------
Syntax
------
```
function fnName(param1 = defaultValue1, /\* β¦ ,\*/ paramN = defaultValueN) {
// β¦
}
```
Description
-----------
In JavaScript, function parameters default to [`undefined`](../global_objects/undefined). However, it's often useful to set a different default value. This is where default parameters can help.
In the following example, if no value is provided for `b` when `multiply` is called, `b`'s value would be `undefined` when evaluating `a * b` and `multiply` would return `NaN`.
```
function multiply(a, b) {
return a \* b;
}
multiply(5, 2); // 10
multiply(5); // NaN !
```
In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are `undefined`. In the following example, `b` is set to `1` if `multiply` is called with only one argument:
```
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a \* b;
}
multiply(5, 2); // 10
multiply(5); // 5
```
With default parameters, checks in the function body are no longer necessary. Now, you can assign `1` as the default value for `b` in the function head:
```
function multiply(a, b = 1) {
return a \* b;
}
multiply(5, 2); // 10
multiply(5); // 5
multiply(5, undefined); // 5
```
Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.
```
function f(x = 1, y) {
return [x, y];
}
f(); // [1, undefined]
f(2); // [2, undefined]
```
**Note:** Parameters after the first default parameter will not contribute to the function's [`length`](../global_objects/function/length).
The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.
This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time [`ReferenceError`](../global_objects/referenceerror). This also includes [`var`](../statements/var)-declared variables in the function body.
For example, the following function will throw a `ReferenceError` when invoked, because the default parameter value does not have access to the child scope of the function body:
```
function f(a = go()) {
function go() {
return ":P";
}
}
f(); // ReferenceError: go is not defined
```
This function will print the value of the *parameter* `a`, because the variable `var a` is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to `b`.
```
function f(a, b = () => console.log(a)) {
var a = 1;
b();
}
f(); // undefined
f(5); // 5
```
Examples
--------
### Passing undefined vs. other falsy values
In the second call in this example, even if the first argument is set explicitly to `undefined` (though not `null` or other [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) values), the value of the `num` argument is still the default.
```
function test(num = 1) {
console.log(typeof num);
}
test(); // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)
// test with other falsy values:
test(""); // 'string' (num is set to '')
test(null); // 'object' (num is set to null)
```
### Evaluated at call time
The default argument is evaluated at *call time*. Unlike with Python (for example), a new object is created each time the function is called.
```
function append(value, array = []) {
array.push(value);
return array;
}
append(1); // [1]
append(2); // [2], not [1, 2]
```
This even applies to functions and variables:
```
function callSomething(thing = something()) {
return thing;
}
let numberOfTimesCalled = 0;
function something() {
numberOfTimesCalled += 1;
return numberOfTimesCalled;
}
callSomething(); // 1
callSomething(); // 2
```
### Earlier parameters are available to later default parameters
Parameters defined earlier (to the left) are available to later default parameters:
```
function greet(name, greeting, message = `${greeting}${name}`) {
return [name, greeting, message];
}
greet("David", "Hi"); // ["David", "Hi", "Hi David"]
greet("David", "Hi", "Happy Birthday!"); // ["David", "Hi", "Happy Birthday!"]
```
This functionality can be approximated like this, which demonstrates how many edge cases are handled:
```
function go() {
return ":P";
}
function withDefaults(
a,
b = 5,
c = b,
d = go(),
e = this,
f = arguments,
g = this.value,
) {
return [a, b, c, d, e, f, g];
}
function withoutDefaults(a, b, c, d, e, f, g) {
switch (arguments.length) {
case 1:
b = 5;
case 2:
c = b;
case 3:
d = go();
case 4:
e = this;
case 5:
f = arguments;
case 6:
g = this.value;
}
return [a, b, c, d, e, f, g];
}
withDefaults.call({ value: "=^\_^=" });
// [undefined, 5, 5, ":P", {value:"=^\_^="}, arguments, "=^\_^="]
withoutDefaults.call({ value: "=^\_^=" });
// [undefined, 5, 5, ":P", {value:"=^\_^="}, arguments, "=^\_^="]
```
### Destructured parameter with default value assignment
You can use default value assignment with the [destructuring assignment](../operators/destructuring_assignment) syntax.
A common way of doing that is to set an empty object/array as the default value the destructured parameter; for example: `[x = 1, y = 2] = []`. This makes it possible to pass nothing to the function and still have those values prefilled:
```
function preFilledArray([x = 1, y = 2] = []) {
return x + y;
}
preFilledArray(); // 3
preFilledArray([]); // 3
preFilledArray([2]); // 4
preFilledArray([2, 3]); // 5
// Works the same for objects:
function preFilledObject({ z = 3 } = {}) {
return z;
}
preFilledObject(); // 3
preFilledObject({}); // 3
preFilledObject({ z: 2 }); // 2
```
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 |
| `Default_parameters` | 49 | 14 | 15 | No | 36 | 10 | 49 | 49 | 15 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `destructured_parameter_with_default_value_assignment` | 49 | 14 | 41 | No | 36 | 10 | 49 | 49 | 41 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `parameters_without_defaults_after_default_parameters` | 49 | 14 | 26 | No | 36 | 10 | 49 | 49 | 26 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Original proposal at ecmascript.org](https://web.archive.org/web/20161222115423/http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values)
| programming_docs |
javascript setter setter
======
The `set` syntax binds an object property to a function to be called when there is an attempt to set that property. It can also be used in [classes](../classes).
Try it
------
Syntax
------
```
{ set prop(val) { /\* β¦ \*/ } }
{ set [expression](val) { /\* β¦ \*/ } }
```
### Parameters
`prop` The name of the property to bind to the given function.
`val` An alias for the variable that holds the value attempted to be assigned to `prop`.
`expression` You can also use expressions for a computed property name to bind to the given function.
Description
-----------
In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.
Note the following when working with the `set` syntax:
* It can have an identifier which is either a number or a string;
* It must have exactly one parameter (see [Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments](https://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/) for more information)
Examples
--------
### Defining a setter on new objects in object initializers
The following example define a pseudo-property `current` of object `language`. When `current` is assigned a value, it updates `log` with that value:
```
const language = {
set current(name) {
this.log.push(name);
},
log: []
}
language.current = 'EN';
console.log(language.log); // ['EN']
language.current = 'FA';
console.log(language.log); // ['EN', 'FA']
```
Note that `current` is not defined, and any attempts to access it will result in `undefined`.
### Using setters in classes
You can use the exact same syntax to define public instance setters that are available on class instances. In classes, you don't need the comma separator between methods.
```
class ClassWithGetSet {
#msg = "hello world";
get msg() {
return this.#msg;
}
set msg(x) {
this.#msg = `hello ${x}`;
}
}
const instance = new ClassWithGetSet();
console.log(instance.msg); // "hello world"
instance.msg = "cake";
console.log(instance.msg); // "hello cake"
```
Setter properties are defined on the `prototype` property of the class and are thus shared by all instances of the class. Unlike setter properties in object literals, setter properties in classes are not enumerable.
Static setters and private setters use similar syntaxes, which are described in the [`static`](../classes/static) and [private class features](../classes/private_class_fields) pages.
### Removing a setter with the `delete` operator
If you want to remove the setter, you can just [`delete`](../operators/delete) it:
```
delete language.current;
```
### Defining a setter on existing objects using `defineProperty`
To append a setter to an *existing* object, use [`Object.defineProperty()`](../global_objects/object/defineproperty).
```
const o = {a: 0};
Object.defineProperty(o, 'b', {
set(x) { this.a = x / 2; }
});
o.b = 10;
// Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.a); // 5
```
### Using a computed property name
```
const expr = 'foo';
const obj = {
baz: 'bar',
set [expr](v) { this.baz = v; }
};
console.log(obj.baz); // "bar"
obj.foo = 'baz';
// Run the setter
console.log(obj.baz); // "baz"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-method-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-method-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 |
| `set` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 | 1.0 | 0.10.0 |
| `computed_property_names` | 46 | 12 | 34 | No | 47 | 9.1 | 46 | 46 | 34 | 33 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Getter](get)
* [`delete`](../operators/delete)
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
* [`__defineGetter__`](../global_objects/object/__definegetter__)
* [`__defineSetter__`](../global_objects/object/__definesetter__)
* [Defining getters and setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#defining_getters_and_setters) in JavaScript Guide
javascript Method definitions Method definitions
==================
**Method definition** is a shorter syntax for defining a function property in an object initializer. It can also be used in [classes](../classes).
Try it
------
Syntax
------
```
({
property(parameters) {},
\*generator(parameters) {},
async property(parameters) {},
async \*generator(parameters) {},
// with computed keys
[expression](parameters) {},
\*[expression](parameters) {},
async [expression](parameters) {},
async \*[expression](parameters) {},
})
```
Description
-----------
The shorthand syntax is similar to the [getter](get) and [setter](set) syntax.
Given the following code:
```
const obj = {
foo: function () {
// β¦
},
bar: function () {
// β¦
},
};
```
You are now able to shorten this to:
```
const obj = {
foo() {
// β¦
},
bar() {
// β¦
},
};
```
[`function*`](../statements/function*), [`async function`](../statements/async_function), and [`async function*`](../statements/async_function*) properties all have their respective method syntaxes; see examples below.
However, note that the method syntax is not equivalent to a normal property with a function as its value β there are semantic differences. This makes methods defined in object literals more consistent with methods in [classes](../classes).
### Method definitions are not constructable
Methods cannot be constructors! They will throw a [`TypeError`](../global_objects/typeerror) if you try to instantiate them. On the other hand, a property created as a function can be used as a constructor.
```
const obj = {
method() {},
};
new obj.method(); // TypeError: obj.method is not a constructor
```
### Using super in method definitions
Only functions defined as methods have access to the [`super`](../operators/super) keyword. `super.prop` looks up the property on the prototype of the object that the method was initialized on.
```
const obj = {
\_\_proto\_\_: {
prop: "foo",
},
method: function () {
console.log(super.prop); // SyntaxError: 'super' keyword unexpected here
},
};
```
Examples
--------
### Using method definitions
```
const obj = {
a: "foo",
b() {
return this.a;
},
};
console.log(obj.b()); // "foo"
```
### Method definitions in classes
You can use the exact same syntax to define public instance methods that are available on class instances. In classes, you don't need the comma separator between methods.
```
class ClassWithPublicInstanceMethod {
publicMethod() {
return "hello world";
}
}
const instance = new ClassWithPublicInstanceMethod();
console.log(instance.publicMethod()); // "hello world"
```
Public instance methods are defined on the `prototype` property of the class and are thus shared by all instances of the class. They are writable, non-enumerable, and configurable.
Inside instance methods, [`this`](../operators/this) and [`super`](../operators/super) work like in normal methods. Usually, `this` refers to the instance itself. In subclasses, `super` lets you access the prototype of the object that the method is attached to, allowing you to call methods from the superclass.
```
class BaseClass {
msg = "hello world";
basePublicMethod() {
return this.msg;
}
}
class SubClass extends BaseClass {
subPublicMethod() {
return super.basePublicMethod();
}
}
const instance = new SubClass();
console.log(instance.subPublicMethod()); // "hello world"
```
Static methods and private methods use similar syntaxes, which are described in the [`static`](../classes/static) and [private class features](../classes/private_class_fields) pages.
### Computed property names
The method syntax also supports [computed property names](../operators/object_initializer#computed_property_names).
```
const bar = {
foo0: function() {
return 0;
},
foo1() {
return 1;
},
["foo" + 2]() {
return 2;
},
};
console.log(bar.foo0()); // 0
console.log(bar.foo1()); // 1
console.log(bar.foo2()); // 2
```
### Generator methods
Note that the asterisk (`*`) in the generator method syntax must be *before* the generator property name. (That is, `* g(){}` will work, but `g *(){}` will not.)
```
// Using a named property
const obj2 = {
g: function\* () {
let index = 0;
while (true) {
yield index++;
}
},
};
// The same object using shorthand syntax
const obj2 = {
\*g() {
let index = 0;
while (true) {
yield index++;
}
},
};
const it = obj2.g();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
```
### Async methods
```
// Using a named property
const obj3 = {
f: async function () {
await somePromise;
},
};
// The same object using shorthand syntax
const obj3 = {
async f() {
await somePromise;
},
};
```
### Async generator methods
```
const obj4 = {
f: async function\* () {
yield 1;
yield 2;
yield 3;
},
};
// The same object using shorthand syntax
const obj4 = {
async \*f() {
yield 1;
yield 2;
yield 3;
},
};
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-method-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-method-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 |
| `Method_definitions` | 39 | 12 | 34 | No | 26 | 9 | 39 | 39 | 34 | 26 | 9 | 4.0 | 1.0 | 4.0.0 |
| `async_generator_methods` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
| `async_methods` | 55 | 15 | 52 | No | 42 | 10.1 | 55 | 55 | 52 | 42 | 10.3 | 6.0 | 1.0 | 7.6.0
7.0.0 |
| `generator_methods_not_constructable` | 42 | 13 | 43 | No | 29 | 9.1 | 42 | 42 | 43 | 29 | 9.3 | 4.0 | 1.0 | 6.0.0 |
See also
--------
* [`get`](get)
* [`set`](set)
* [Lexical grammar](../lexical_grammar)
javascript getter getter
======
The `get` syntax binds an object property to a function that will be called when that property is looked up. It can also be used in [classes](../classes).
Try it
------
Syntax
------
```
{ get prop() { /\* β¦ \*/ } }
{ get [expression]() { /\* β¦ \*/ } }
```
### Parameters
`prop` The name of the property to bind to the given function.
`expression` You can also use expressions for a computed property name to bind to the given function.
Description
-----------
Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a *getter*.
It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it *is* possible to use a getter and a setter in conjunction to create a type of pseudo-property.
Note the following when working with the `get` syntax:
* It can have an identifier which is either a number or a string;
* It must have exactly zero parameters (see [Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments](https://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/) for more information);
* It must not appear in an object literal with another `get` e.g. the following is forbidden
```
{
get x() { }, get x() { }
}
```
* It must not appear with a data entry for the same property e.g. the following is forbidden
```
{
x: /\* β¦ \*/, get x() { /\* β¦ \*/ }
}
```
Examples
--------
### Defining a getter on new objects in object initializers
This will create a pseudo-property `latest` for object `obj`, which will return the last array item in `log`.
```
const obj = {
log: ['example','test'],
get latest() {
if (this.log.length === 0) return undefined;
return this.log[this.log.length - 1];
}
}
console.log(obj.latest); // "test"
```
Note that attempting to assign a value to `latest` will not change it.
### Using getters in classes
You can use the exact same syntax to define public instance getters that are available on class instances. In classes, you don't need the comma separator between methods.
```
class ClassWithGetSet {
#msg = "hello world";
get msg() {
return this.#msg;
}
set msg(x) {
this.#msg = `hello ${x}`;
}
}
const instance = new ClassWithGetSet();
console.log(instance.msg); // "hello world"
instance.msg = "cake";
console.log(instance.msg); // "hello cake"
```
Getter properties are defined on the `prototype` property of the class and are thus shared by all instances of the class. Unlike getter properties in object literals, getter properties in classes are not enumerable.
Static setters and private setters use similar syntaxes, which are described in the [`static`](../classes/static) and [private class features](../classes/private_class_fields) pages.
### Deleting a getter using the `delete` operator
If you want to remove the getter, you can just [`delete`](../operators/delete) it:
```
delete obj.latest;
```
### Defining a getter on existing objects using `defineProperty`
To append a getter to an existing object later at any time, use [`Object.defineProperty()`](../global_objects/object/defineproperty).
```
const o = {a: 0};
Object.defineProperty(o, 'b', { get() { return this.a + 1; } });
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
```
### Using a computed property name
```
const expr = 'foo';
const obj = {
get [expr]() { return 'bar'; }
};
console.log(obj.foo); // "bar"
```
### Defining static getters
```
class MyConstants {
static get foo() {
return 'foo';
}
}
console.log(MyConstants.foo); // 'foo'
MyConstants.foo = 'bar';
console.log(MyConstants.foo); // 'foo', a static getter's value cannot be changed
```
### Smart / self-overwriting / lazy getters
Getters give you a way to *define* a property of an object, but they do not *calculate* the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed. If it is never needed, you never pay the cost.
An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are *smart* (or *[memoized](https://en.wikipedia.org/wiki/Memoization)*) getters. The value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:
* If the calculation of a property value is expensive (takes much RAM or CPU time, spawns worker threads, retrieves remote file, etc.).
* If the value isn't needed just now. It will be used later, or in some case it's not used at all.
* If it's used, it will be accessed several times, and there is no need to re-calculate that value will never be changed or shouldn't be re-calculated.
**Note:** This means that you shouldn't write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value.
Note that getters are not "lazy" or "memoized" by nature; you must implement this technique if you desire this behavior.
In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned.
```
const obj = {
get notifier() {
delete this.notifier;
return this.notifier = document.getElementById('bookmarked-notification-anchor');
},
}
```
### get vs. defineProperty
While using the `get` keyword and [`Object.defineProperty()`](../global_objects/object/defineproperty) have similar results, there is a subtle difference between the two when used on [`classes`](../classes).
When using `get` the property will be defined on the instance's prototype, while using [`Object.defineProperty()`](../global_objects/object/defineproperty) the property will be defined on the instance it is applied to.
```
class Example {
get hello() {
return 'world';
}
}
const obj = new Example();
console.log(obj.hello);
// "world"
console.log(Object.getOwnPropertyDescriptor(obj, 'hello'));
// undefined
console.log(
Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(obj), 'hello'
)
);
// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-method-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-method-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 |
| `get` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 | 1.0 | 0.10.0 |
| `computed_property_names` | 46 | 12 | 34 | No | 47 | 9.1 | 46 | 46 | 34 | 33 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Setter](set)
* [`delete`](../operators/delete)
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
* [`Object.prototype.__defineGetter__()`](../global_objects/object/__definegetter__)
* [`Object.prototype.__defineSetter__()`](../global_objects/object/__definesetter__)
* [Defining getters and setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#defining_getters_and_setters) in JavaScript Guide
javascript The arguments object The arguments object
====================
`arguments` is an `Array`-like object accessible inside [functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions) that contains the values of the arguments passed to that function.
Try it
------
Description
-----------
**Note:** In modern code, [rest parameters](rest_parameters) should be preferred.
The `arguments` object is a local variable available within all non-[arrow](arrow_functions) functions. You can refer to a function's arguments inside that function by using its `arguments` object. It has entries for each argument the function was called with, with the first entry's index at `0`.
For example, if a function is passed 3 arguments, you can access them as follows:
```
arguments[0] // first argument
arguments[1] // second argument
arguments[2] // third argument
```
The `arguments` object is useful for functions called with more arguments than they are formally declared to accept, called [*variadic functions*](https://en.wikipedia.org/wiki/Variadic_function), such as [`Math.min()`](../global_objects/math/min). This example function accepts any number of string arguments and returns the longest one:
```
function longestString() {
let longest = '';
for (let i = 0; i < arguments.length; i++) {
if (arguments[i].length > longest.length) {
longest = arguments[i];
}
}
return longest;
}
```
You can use [`arguments.length`](arguments/length) to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's [`length`](../global_objects/function/length) property.
### Assigning to indices
Each argument index can also be set or reassigned:
```
arguments[1] = 'new value';
```
Non-strict functions that only has simple parameters (that is, no rest, default, or destructured parameters) will sync the new value of parameters with the `arguments` object, and vice versa:
```
function func(a) {
arguments[0] = 99; // updating arguments[0] also updates a
console.log(a);
}
func(10); // 99
function func2(a) {
a = 99; // updating a also updates arguments[0]
console.log(arguments[0]);
}
func2(10); // 99
```
Non-strict functions that *are* passed [rest](rest_parameters), [default](default_parameters), or [destructured](../operators/destructuring_assignment) parameters will not sync new values assigned to parameters in the function body with the `arguments` object. Instead, the `arguments` object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called.
```
function funcWithDefault(a = 55) {
arguments[0] = 99; // updating arguments[0] does not also update a
console.log(a);
}
funcWithDefault(10); // 10
function funcWithDefault2(a = 55) {
a = 99; // updating a does not also update arguments[0]
console.log(arguments[0]);
}
funcWithDefault2(10); // 10
// An untracked default parameter
function funcWithDefault3(a = 55) {
console.log(arguments[0]);
console.log(arguments.length);
}
funcWithDefault3(); // undefined; 0
```
This is the same behavior exhibited by all [strict-mode functions](../strict_mode#making_eval_and_arguments_simpler), regardless of the type of parameters they are passed. That is, assigning new values to parameters in the body of the function never affects the `arguments` object, nor will assigning new values to the `arguments` indices affect the value of parameters, even when the function only has simple parameters.
**Note:** You cannot write a `"use strict";` directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw [a syntax error](../errors/strict_non_simple_params).
### arguments is an array-like object
`arguments` is an array-like object, which means that `arguments` has a [`length`](arguments/length) property and properties indexed from zero, but it doesn't have [`Array`](../global_objects/array)'s built-in methods like [`forEach()`](../global_objects/array/foreach) or [`map()`](../global_objects/array/map). However, it can be converted to a real `Array`, using one of [`slice()`](../global_objects/array/slice), [`Array.from()`](../global_objects/array/from), or [spread syntax](../operators/spread_syntax).
```
const args = Array.prototype.slice.call(arguments);
// or
const args = Array.from(arguments);
// or
const args = [...arguments];
```
For common use cases, using it as an array-like object is sufficient, since it both [is iterable](arguments/@@iterator) and has `length` and number indices. For example, [`Function.prototype.apply()`](../global_objects/function/apply) accepts array-like objects.
```
function midpoint() {
return (Math.min.apply(null, arguments) + Math.max.apply(null, arguments)) / 2;
}
console.log(midpoint(3, 1, 4, 1, 5)); // 3
```
Properties
----------
[`arguments.callee`](arguments/callee) Deprecated
Reference to the currently executing function that the arguments belong to. Forbidden in strict mode.
[`arguments.length`](arguments/length) The number of arguments that were passed to the function.
[`arguments[@@iterator]`](arguments/@@iterator) Returns a new [Array iterator](../global_objects/array/@@iterator) object that contains the values for each index in `arguments`.
Examples
--------
### Defining a function that concatenates several strings
This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.
```
function myConcat(separator) {
const args = Array.prototype.slice.call(arguments, 1);
return args.join(separator);
}
```
You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:
```
// returns "red, orange, blue"
myConcat(', ', 'red', 'orange', 'blue');
// returns "elephant; giraffe; lion; cheetah"
myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
// returns "sage. basil. oregano. pepper. parsley"
myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
```
### Defining a function that creates HTML lists
This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is `"u"` if the list is to be [unordered (bulleted)](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul), or `"o"` if the list is to be [ordered (numbered)](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol). The function is defined as follows:
```
function list(type) {
let html = `<${type}l><li>`;
const args = Array.prototype.slice.call(arguments, 1);
html += args.join('</li><li>');
html += `</li></${type}l>`; // end list
return html;
}
```
You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:
```
const listHTML = list('u', 'One', 'Two', 'Three');
/\* listHTML is:
"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
\*/
```
### Using typeof with arguments
The [`typeof`](../operators/typeof) operator returns `'object'` when used with `arguments`
```
console.log(typeof arguments); // 'object'
```
The type of individual arguments can be determined by indexing `arguments`:
```
console.log(typeof arguments[0]); // returns the type of the first argument
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-arguments-exotic-objects](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-arguments-exotic-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` | 52 | 12 | 46 | No | 39 | 9 | 52 | 52 | 46 | 41 | 9 | 6.0 | 1.0 | 4.0.0 |
| `arguments` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `callee` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `length` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Function`](../global_objects/function)
* [Rest parameters](rest_parameters)
| programming_docs |
javascript arguments.length arguments.length
================
The `arguments.length` data property contains the number of arguments passed to the function.
Value
-----
A non-negative integer.
| Property attributes of `arguments.length` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Description
-----------
The `arguments.length` property provides the number of arguments actually passed to a function. This can be more or less than the defined parameter's count (see [`Function.prototype.length`](../../global_objects/function/length)). For example, for the function below:
```
function func1(a, b, c) {
console.log(arguments.length);
}
```
`func1.length` returns `3`, because `func1` declares three formal parameters. However, `func1(1, 2, 3, 4, 5)` logs `5`, because `func1` was called with five arguments. Similarly, `func1(1)` logs `1`, because `func1` was called with one argument.
Examples
--------
### Using arguments.length
In this example, we define a function that can add two or more numbers together.
```
function adder(base /\*, num1, β¦, numN \*/) {
base = Number(base);
for (let i = 1; i < arguments.length; i++) {
base += Number(arguments[i]);
}
return base;
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-arguments-exotic-objects](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-arguments-exotic-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 |
| `length` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Function`](../../global_objects/function)
* [`Function.prototype.length`](../../global_objects/function/length)
javascript arguments.callee arguments.callee
================
**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.
The `arguments.callee` property contains the currently executing function that the arguments belong to.
**Warning:** Accessing `arguments.callee` in [strict mode](../../strict_mode) will throw a [`TypeError`](../../global_objects/typeerror). If a function must reference itself, either give the function expression a name or use a function declaration.
Value
-----
A reference to the currently executing function.
| Property attributes of `arguments.callee` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
**Note:** `callee` is a data property only in non-strict functions with simple parameters (in which case the `arguments` object is also [auto-syncing](../arguments#assigning_to_indices)). Otherwise, it is an accessor property whose getter and setter both throw a [`TypeError`](../../global_objects/typeerror).
Description
-----------
`callee` is a property of the `arguments` object. It can be used to refer to the currently executing function inside the function body of that function. This is useful when the name of the function is unknown, such as within a function expression with no name (also called "anonymous functions").
(The text below is largely adapted from [a Stack Overflow answer by olliej](https://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript/235760))
Early versions of JavaScript did not allow named function expressions, and for this reason you could not make a recursive function expression.
For example, this syntax worked:
```
function factorial(n) {
return n <= 1 ? 1 : factorial(n - 1) \* n;
}
[1, 2, 3, 4, 5].map(factorial);
```
but:
```
[1, 2, 3, 4, 5].map(function (n) {
return n <= 1 ? 1 : /\* what goes here? \*/ (n - 1) \* n;
});
```
did not. To get around this `arguments.callee` was added so you could do
```
[1, 2, 3, 4, 5].map(function (n) {
return n <= 1 ? 1 : arguments.callee(n - 1) \* n;
});
```
However, the design of `arguments.callee` has multiple issues. The first problem is that the recursive call will get a different `this` value. For example:
```
const global = this;
const sillyFunction = function (recursed) {
if (this !== global) {
console.log('This is: ', this);
} else {
console.log('This is the global');
}
if (!recursed) {
return arguments.callee(true);
}
}
sillyFunction();
// This is the global
// This is: [object Arguments]
```
In addition, references to `arguments.callee` make inlining and tail recursion impossible in the general case. (You can achieve it in select cases through tracing, etc., but even the best code is suboptimal due to checks that would not otherwise be necessary.)
ECMAScript 3 resolved these issues by allowing named function expressions. For example:
```
[1, 2, 3, 4, 5].map(function factorial(n) {
return n <= 1 ? 1 : factorial(n - 1) \* n;
});
```
This has numerous benefits:
* the function can be called like any other from inside your code
* it does not create a variable in the outer scope ([except for IE 8 and below](https://kangax.github.io/nfe/#example_1_function_expression_identifier_leaks_into_an_enclosing_scope))
* it has better performance than accessing the arguments object
Strict mode has banned other properties that leak stack information, like the [`caller`](../../global_objects/function/caller) property of functions. This is because looking at the call stack has one single major effect: it makes a large number of optimizations impossible, or much more difficult. For example, if you cannot guarantee that a function `f` will not call an unknown function, it is not possible to inline `f`.
```
function f(a, b, c, d, e) {
return a ? b \* c : d \* e;
}
```
If the JavaScript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. This means any call site that may have been trivially inlinable accumulates a large number of guards. Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.
Examples
--------
### Using arguments.callee in an anonymous recursive function
A recursive function must be able to refer to itself. Typically, a function refers to itself by its name. However, an anonymous function (which can be created by a [function expression](../../operators/function) or the [`Function` constructor](../../global_objects/function)) does not have a name. Therefore if there is no accessible variable referring to it, the only way the function can refer to itself is by `arguments.callee`.
The following example defines a function, which, in turn, defines and returns a factorial function. This example isn't very practical, and there are nearly no cases where the same result cannot be achieved with [named function expressions](../../operators/function).
```
function create() {
return function (n) {
if (n <= 1) {
return 1;
}
return n \* arguments.callee(n - 1);
};
}
const result = create()(5); // returns 120 (5 \* 4 \* 3 \* 2 \* 1)
```
### Recursion of anonymous functions with a Y-combinator
Although function expressions can now be named, [arrow functions](../arrow_functions) always remain anonymous, which means they cannot reference themselves without being assigned to a variable first. Fortunately, in Lambda calculus there's a very good solution which allows a function to both be anonymous and self-referential. The technique is called a [Y-combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator). Here we will not explain *how* it works, only *that* it works.
```
// The Y-combinator: a utility function!
const Y = (hof) => ((x) => x(x))((x) => hof((y) => x(x)(y)));
console.log(
[1, 2, 3, 4, 5].map(
// Wrap the higher-order function in the Y-combinator
// "factorial" is not a function's name: it's introduced as a parameter
Y((factorial) => (n) => (n <= 1 ? 1 : factorial(n - 1) \* n))
)
);
// [ 1, 2, 6, 24, 120 ]
```
**Note:** This method allocates a new closure for every iteration, which may significantly increase memory usage. It's only here to demonstrate the possibility, but should be avoided in production. Use a temporary variable or a named function expression instead.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-arguments-exotic-objects](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-arguments-exotic-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 |
| `callee` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Function`](../../global_objects/function)
javascript arguments[@@iterator]() arguments[@@iterator]()
=======================
The `@@iterator` method of the [`arguments`](../arguments) object implements the [iterable protocol](../../iteration_protocols) and allows `arguments` 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 `arguments` object.
The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](../../global_objects/array/values) property (and also the same as [`Array.prototype[@@iterator]`](../../global_objects/array/@@iterator)).
Syntax
------
```
arguments[Symbol.iterator]()
```
### Return value
The same return value as [`Array.prototype.values()`](../../global_objects/array/values): a new iterable iterator object that yields the value of each index in the `arguments` object.
Examples
--------
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `arguments` [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.
```
function f() {
for (const letter of arguments) {
console.log(letter);
}
}
f("w", "y", "k", "o", "p");
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-createunmappedargumentsobject](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-createunmappedargumentsobject) |
| [ECMAScript Language Specification # sec-createmappedargumentsobject](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-createmappedargumentsobject) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | 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` | 52 | 12 | 46 | No | 39 | 9 | 52 | 52 | 46 | 41 | 9 | 6.0 | 1.0 | 4.0.0 |
See also
--------
* [`Array.prototype.values()`](../../global_objects/array/values)
javascript TypeError: invalid Array.prototype.sort argument TypeError: invalid Array.prototype.sort argument
================================================
The JavaScript exception "invalid Array.prototype.sort argument" occurs when the argument of [`Array.prototype.sort()`](../global_objects/array/sort) isn't either [`undefined`](../global_objects/undefined) or a function which compares its operands.
Message
-------
```
TypeError: The comparison function must be either a function or undefined (V8-based)
TypeError: invalid Array.prototype.sort argument (Firefox)
TypeError: Array.prototype.sort requires the comparator argument to be a function or undefined (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
The argument of [`Array.prototype.sort()`](../global_objects/array/sort) is expected to be either [`undefined`](../global_objects/undefined) or a function which compares its operands.
Examples
--------
### Invalid cases
```
[1, 3, 2].sort(5); // TypeError
const cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y };
[1, 3, 2].sort(cmp[this.key] || 'asc'); // TypeError
```
### Valid cases
```
[1, 3, 2].sort(); // [1, 2, 3]
const cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y };
[1, 3, 2].sort(cmp[this.key || 'asc']); // [1, 2, 3]
```
See also
--------
* [`Array.prototype.sort()`](../global_objects/array/sort)
javascript SyntaxError: "use strict" not allowed in function with non-simple parameters SyntaxError: "use strict" not allowed in function with non-simple parameters
============================================================================
The JavaScript exception "`'use strict'` not allowed in function" occurs when a `"use strict"` directive is used at the top of a function with [default parameters](../functions/default_parameters), [rest parameters](../functions/rest_parameters), or [destructuring parameters](../operators/destructuring_assignment).
Message
-------
```
SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list (V8-based)
SyntaxError: "use strict" not allowed in function with default parameter (Firefox)
SyntaxError: "use strict" not allowed in function with rest parameter (Firefox)
SyntaxError: "use strict" not allowed in function with destructuring parameter (Firefox)
SyntaxError: 'use strict' directive not allowed inside a function with a non-simple parameter list. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
A `"use strict"` directive is written at the top of a function that has one of the following parameters:
* [Default parameters](../functions/default_parameters)
* [Rest parameters](../functions/rest_parameters)
* [Destructuring parameters](../operators/destructuring_assignment)
A `"use strict"` directive is not allowed at the top of such functions per the ECMAScript specification.
Examples
--------
### Function statement
In this case, the function `sum` has default parameters `a=1` and `b=2`:
```
function sum(a = 1, b = 2) {
// SyntaxError: "use strict" not allowed in function with default parameter
'use strict';
return a + b;
}
```
If the function should be in [strict mode](../strict_mode), and the entire script or enclosing function is also okay to be in strict mode, you can move the `"use strict"` directive outside of the function:
```
'use strict';
function sum(a = 1, b = 2) {
return a + b;
}
```
### Function expression
A function expression can use yet another workaround:
```
const sum = function sum([a, b]) {
// SyntaxError: "use strict" not allowed in function with destructuring parameter
'use strict';
return a + b;
};
```
This can be converted to the following expression:
```
const sum = (function() {
'use strict';
return function sum([a, b]) {
return a + b;
};
})();
```
### Arrow function
If an arrow function needs to access the `this` variable, you can use the arrow function as the enclosing function:
```
const callback = (...args) => {
// SyntaxError: "use strict" not allowed in function with rest parameter
'use strict';
return this.run(args);
};
```
This can be converted to the following expression:
```
const callback = (() => {
'use strict';
return (...args) => {
return this.run(args);
};
})();
```
See also
--------
* [Strict mode](../strict_mode)
* [function statement](../statements/function)
* [function expression](../operators/function)
* [Default parameters](../functions/default_parameters)
* [Rest parameters](../functions/rest_parameters)
* [Destructuring parameters](../operators/destructuring_assignment)
javascript TypeError: can't redefine non-configurable property "x" TypeError: can't redefine non-configurable property "x"
=======================================================
The JavaScript exception "can't redefine non-configurable property" occurs when it was attempted to redefine a property, but that property is [non-configurable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties).
Message
-------
```
TypeError: Cannot redefine property: "x" (V8-based)
TypeError: can't redefine non-configurable property "x" (Firefox)
TypeError: Attempting to change value of a readonly property. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
It was attempted to redefine a property, but that property is [non-configurable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties). The `configurable` attribute controls whether the property can be deleted from the object and whether its attributes (other than `writable`) can be changed. Usually, properties in an object created by an [object initializer](../operators/object_initializer) are configurable. However, for example, when using [`Object.defineProperty()`](../global_objects/object/defineproperty), the property isn't configurable by default.
Examples
--------
### Non-configurable properties created by Object.defineProperty
The [`Object.defineProperty()`](../global_objects/object/defineproperty) creates non-configurable properties if you haven't specified them as configurable.
```
const obj = Object.create({});
Object.defineProperty(obj, "foo", {value: "bar"});
Object.defineProperty(obj, "foo", {value: "baz"});
// TypeError: can't redefine non-configurable property "foo"
```
You will need to set the "foo" property to configurable, if you intend to redefine it later in the code.
```
const obj = Object.create({});
Object.defineProperty(obj, "foo", {value: "bar", configurable: true});
Object.defineProperty(obj, "foo", {value: "baz", configurable: true});
```
See also
--------
* [[[Configurable]]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties)
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
javascript SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
===================================================================================
The JavaScript warning "Using `//@` to indicate sourceURL pragmas is deprecated. Use `//#` instead" occurs when there is a deprecated source map syntax in a JavaScript source.
Message
-------
```
Warning: SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
Warning: SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
```
Error type
----------
A warning that a [`SyntaxError`](../global_objects/syntaxerror) occurred. JavaScript execution won't be halted.
What went wrong?
----------------
There is a deprecated source map syntax in a JavaScript source.
JavaScript sources are often combined and minified to make delivering them from the server more efficient. With [source maps](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html), the debugger can map the code being executed to the original source files.
The source map specification changed the syntax due to a conflict with IE whenever it was found in the page after `//@cc_on` was interpreted to turn on conditional compilation in the IE JScript engine. The [conditional compilation comment](https://stackoverflow.com/questions/24473882/what-does-this-comment-cc-on-0-do-inside-an-if-statement-in-javascript) in IE is a little known feature, but it broke source maps with [jQuery](https://bugs.jquery.com/ticket/13274) and other libraries.
Examples
--------
### Deprecated syntax
Syntax with the "@" sign is deprecated.
```
//@ sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```
### Standard syntax
Use the "#" sign instead.
```
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```
Or, alternatively, you can set a [`SourceMap`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/SourceMap) header to your JavaScript file to avoid having a comment at all:
```
SourceMap: /path/to/file.js.map
```
See also
--------
* [How to use a source map β Firefox Tools documentation](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html)
* [Introduction to source maps (2012)](https://developer.chrome.com/blog/sourcemaps/)
* [`SourceMap`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/SourceMap)
| programming_docs |
javascript RangeError: precision is out of range RangeError: precision is out of range
=====================================
The JavaScript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into `toFixed` or `toPrecision`.
Message
-------
```
RangeError: toExponential() argument must be between 0 and 100 (V8-based & Safari)
RangeError: toFixed() digits argument must be between 0 and 100 (V8-based & Safari)
RangeError: toPrecision() argument must be between 1 and 100 (V8-based & Safari)
RangeError: precision -1 out of range (Firefox)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror)What went wrong?
----------------
There was an out of range precision argument in one of these methods:
* [`Number.prototype.toExponential()`](../global_objects/number/toexponential), which requires the arguments to be between 0 and 100, inclusive.
* [`Number.prototype.toFixed()`](../global_objects/number/tofixed), which requires the arguments to be between 0 and 100, inclusive.
* [`Number.prototype.toPrecision()`](../global_objects/number/toprecision), which requires the arguments to be between 1 and 100, inclusive.
Examples
--------
### Invalid cases
```
77.1234.toExponential(-1); // RangeError
77.1234.toExponential(101); // RangeError
2.34.toFixed(-100); // RangeError
2.34.toFixed(1001); // RangeError
1234.5.toPrecision(-1); // RangeError
1234.5.toPrecision(101); // RangeError
```
### Valid cases
```
77.1234.toExponential(4); // 7.7123e+1
77.1234.toExponential(2); // 7.71e+1
2.34.toFixed(1); // 2.3
2.35.toFixed(1); // 2.4 (note that it rounds up in this case)
5.123456.toPrecision(5); // 5.1235
5.123456.toPrecision(2); // 5.1
5.123456.toPrecision(1); // 5
```
See also
--------
* [`Number.prototype.toExponential()`](../global_objects/number/toexponential)
* [`Number.prototype.toFixed()`](../global_objects/number/tofixed)
* [`Number.prototype.toPrecision()`](../global_objects/number/toprecision)
javascript TypeError: "x" is read-only TypeError: "x" is read-only
===========================
The JavaScript [strict mode](../strict_mode)-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property.
Message
-------
```
TypeError: Cannot assign to read only property 'x' of #<Object> (V8-based)
TypeError: "x" is read-only (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror) in [strict mode](../strict_mode) only.
What went wrong?
----------------
The global variable or object property that was assigned to is a read-only property. (Technically, it is a [non-writable data property](../global_objects/object/defineproperty#writable_attribute).)
This error happens only in [strict mode code](../strict_mode). In non-strict code, the assignment is silently ignored.
Examples
--------
### Invalid cases
Read-only properties are not super common, but they can be created using [`Object.defineProperty()`](../global_objects/object/defineproperty) or [`Object.freeze()`](../global_objects/object/freeze).
```
'use strict';
const obj = Object.freeze({ name: 'Elsa', score: 157 });
obj.score = 0; // TypeError
'use strict';
Object.defineProperty(this, 'LUNG\_COUNT', { value: 2, writable: false });
LUNG\_COUNT = 3; // TypeError
'use strict';
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray[0]++; // TypeError
```
There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant.
```
'use strict';
Math.PI = 4; // TypeError
```
Sorry, you can't do that.
The global variable `undefined` is also read-only, so you can't silence the infamous "undefined is not a function" error by doing this:
```
'use strict';
undefined = function() {}; // TypeError: "undefined" is read-only
```
### Valid cases
```
'use strict';
let obj = Object.freeze({ name: 'Score', points: 157 });
obj = { name: obj.name, points: 0 }; // replacing it with a new object works
```
See also
--------
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
* [`Object.freeze()`](../global_objects/object/freeze)
javascript TypeError: can't convert BigInt to number TypeError: can't convert BigInt to number
=========================================
The JavaScript exception "can't convert BigInt to number" occurs when an arithmetic operation involves a mix of [`BigInt`](../global_objects/bigint) and [`Number`](../global_objects/number) values.
Message
-------
```
TypeError: Cannot mix BigInt and other types, use explicit conversions (V8-based)
TypeError: BigInts have no unsigned right shift, use >> instead (V8-based)
TypeError: can't convert BigInt to number (Firefox)
TypeError: Invalid mix of BigInt and other type in addition/multiplication/β¦. (Safari)
TypeError: BigInt does not support >>> operator (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror).
What went wrong?
----------------
The two sides of an arithmetic operator must both be BigInts or both not. If an operation involves a mix of BigInts and numbers, it's ambiguous whether the result should be a BigInt or number, since there may be loss of precision in both cases.
The error can also happen if the [unsigned right shift operator (`>>>`)](../operators/unsigned_right_shift) is used between two BigInts. In Firefox, the message is the same: "can't convert BigInt to number".
Examples
--------
### Mixing numbers and BigInts in operations
```
const sum = 1n + 1;
// TypeError: can't convert BigInt to number
```
Instead, explicitly coerce one side to a BigInt or number.
```
const sum = 1n + BigInt(1);
const sum2 = Number(1n) + 1;
```
### Using unsigned right shift on BigInts
```
const a = 4n >>> 2n;
// TypeError: can't convert BigInt to number
```
Use normal right shift instead.
```
const a = 4n >> 2n;
```
See also
--------
* [`BigInt`](../global_objects/bigint)
javascript SyntaxError: Malformed formal parameter SyntaxError: Malformed formal parameter
=======================================
The JavaScript exception "malformed formal parameter" occurs when the argument list of a [`Function()`](../global_objects/function) constructor call is invalid somehow.
Message
-------
```
SyntaxError: Expected {x} (Edge)
SyntaxError: malformed formal parameter (Firefox)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
There is a [`Function()`](../global_objects/function) constructor with at least two arguments passed in the code. The last argument is the source code for the new function you're creating. All the rest make up your new function's argument list.
The argument list is invalid somehow. Perhaps you accidentally picked a keyword like `if` or `var` as an argument name, or perhaps there's some stray punctuation in your argument list. Or maybe you accidentally passed an invalid value, like a number or object.
### OK, that fixed my problem. But why didn't you say that in the first place?
Admittedly the wording in the error message is slightly strange. "Formal parameter" is a fancy way of saying "function argument". And we use the word "malformed" because all Firefox engineers are huge fans of 19th-century Gothic horror novels.
Examples
--------
### Invalid cases
```
const f = Function('x y', 'return x + y;');
// SyntaxError (missing a comma)
const g = Function(37, "alert('OK')");
// SyntaxError (numbers can't be argument names)
```
### Valid cases
```
const f = Function('x, y', 'return x + y;'); // correctly punctuated
// if you can, avoid using Function - this is much faster
const g = function (x) { return x; };
```
See also
--------
* [`Function()`](../global_objects/function)
* [About functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
* [*Frankenstein* by Mary Wollstonecraft Shelley, full e-text](https://www.gutenberg.org/ebooks/84) ("Cursed (although I curse myself) be the hands that formed you! You have made me wretched beyond expression. You have left me no power to consider whether I am just to you or not. Begone! Relieve me from the sight of your detested form.")
javascript ReferenceError: reference to undefined property "x" ReferenceError: reference to undefined property "x"
===================================================
The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.
Message
-------
```
ReferenceError: reference to undefined property "x" (Firefox)
```
Error type
----------
(Firefox only) [`ReferenceError`](../global_objects/referenceerror) warning which is reported only if `javascript.options.strict` preference is set to `true`.
What went wrong?
----------------
The script attempted to access an object property which doesn't exist. There are two ways to access properties; see the [property accessors](../operators/property_accessors) reference page to learn more about them.
Examples
--------
### Invalid cases
In this case, the property `bar` is an undefined property, so a `ReferenceError` will occur.
```
const foo = {};
foo.bar; // ReferenceError: reference to undefined property "bar"
```
### Valid cases
To avoid the error, you need to either add a definition for `bar` to the object or check for the existence of the `bar` property before trying to access it; ways to do that include using the [`in`](../operators/in) operator, or the [`Object.hasOwn()`](../global_objects/object/hasown) method, like this:
```
const foo = {};
// Define the bar property
foo.bar = 'moon';
console.log(foo.bar); // "moon"
// Test to be sure bar exists before accessing it
if (Object.hasOwn(foo, 'bar')) {
console.log(foo.bar);
}
```
See also
--------
* [Property accessors](../operators/property_accessors)
javascript TypeError: Reduce of empty array with no initial value TypeError: Reduce of empty array with no initial value
======================================================
The JavaScript exception "reduce of empty array with no initial value" occurs when a reduce function is used.
Message
-------
```
TypeError: Reduce of empty array with no initial value (V8-based & Firefox & Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
In JavaScript, there are several reduce functions:
* [`Array.prototype.reduce()`](../global_objects/array/reduce), [`Array.prototype.reduceRight()`](../global_objects/array/reduceright) and
* [`TypedArray.prototype.reduce()`](../global_objects/typedarray/reduce), [`TypedArray.prototype.reduceRight()`](../global_objects/typedarray/reduceright)).
These functions optionally take an `initialValue` (which will be used as the first argument to the first call of the `callback`). However, if no initial value is provided, it will use the first element of the [`Array`](../global_objects/array) or [`TypedArray`](../global_objects/typedarray) as the initial value. This error is raised when an empty array is provided because no initial value can be returned in that case.
Examples
--------
### Invalid cases
This problem appears frequently when combined with a filter ([`Array.prototype.filter()`](../global_objects/array/filter), [`TypedArray.prototype.filter()`](../global_objects/typedarray/filter)) which will remove all elements of the list. Thus leaving none to be used as the initial value.
```
const ints = [0, -1, -2, -3, -4, -5];
ints.filter((x) => x > 0) // removes all elements
.reduce((x, y) => x + y) // no more elements to use for the initial value.
```
Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list:
```
const names = document.getElementsByClassName("names");
const name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name);
```
### Valid cases
These problems can be solved in two different ways.
One way is to actually provide an `initialValue` as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation.
```
const ints = [0, -1, -2, -3, -4, -5];
ints.filter((x) => x > 0) // removes all elements
.reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition
```
Another way would be to handle the empty case, either before calling `reduce`, or in the callback after adding an unexpected dummy initial value.
```
const names = document.getElementsByClassName("names");
let nameList1 = "";
if (names.length >= 1) {
nameList1 = Array.prototype.reduce.call(names, (acc, name) => `${acc}, ${name}`);
}
// nameList1 === "" when names is empty.
const nameList2 = Array.prototype.reduce.call(names, (acc, name) => {
if (acc === "") // initial value
return name;
return `${acc}, ${name}`;
}, "");
// nameList2 === "" when names is empty.
```
See also
--------
* [`Array.prototype.reduce()`](../global_objects/array/reduce)
* [`Array.prototype.reduceRight()`](../global_objects/array/reduceright)
* [`TypedArray.prototype.reduce()`](../global_objects/typedarray/reduce)
* [`TypedArray.prototype.reduceRight()`](../global_objects/typedarray/reduceright)
* [`Array`](../global_objects/array)
* [`TypedArray`](../global_objects/typedarray)
* [`Array.prototype.filter()`](../global_objects/array/filter)
* [`TypedArray.prototype.filter()`](../global_objects/typedarray/filter)
javascript SyntaxError: function statement requires a name SyntaxError: function statement requires a name
===============================================
The JavaScript exception "function statement requires a name" occurs when there is a [function statement](../statements/function) in the code that requires a name.
Message
-------
```
SyntaxError: Function statements require a function name (V8-based)
SyntaxError: function statement requires a name (Firefox)
SyntaxError: Function statements must have a name. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
There is a [function statement](../statements/function) in the code that requires a name. You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE), or if the function code is placed correctly in this context at all.
Examples
--------
### Statements vs expressions
A *[function statement](../statements/function)* (or *function declaration*) requires a name. This won't work:
```
function () {
return 'Hello world';
}
// SyntaxError: function statement requires a name
```
You can use a [function expression](../operators/function) (assignment) instead:
```
const greet = function () {
return 'Hello world';
};
```
If your function is intended to be an [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) (Immediately Invoked Function Expression, which is a function that runs as soon as it is defined) you will need to add a few more braces:
```
(function () {
})();
```
### Labeled functions
If you are using function [labels](../statements/label), you will still need to provide a function name after the `function` keyword. This doesn't work:
```
function Greeter() {
german: function () {
return "Moin";
}
}
// SyntaxError: function statement requires a name
```
This would work, for example:
```
function Greeter() {
german: function g() {
return "Moin";
}
}
```
### Object methods
If you intended to create a method of an object, you will need to create an object. The following syntax without a name after the `function` keyword is valid then.
```
const greeter = {
german: function () {
return "Moin";
}
};
// or
const greeter = {
german() {
return "Moin";
}
};
```
### Callback syntax
Also, check your syntax when using callbacks. Brackets and commas can quickly get confusing.
```
promise.then(
function () {
console.log("success");
});
function () {
console.log("error");
}
// SyntaxError: function statement requires a name
```
Correct would be:
```
promise.then(
function () {
console.log("success");
},
function () {
console.log("error");
},
);
```
See also
--------
* [Functions in the JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
* [function statement](../statements/function)
* [function expression](../operators/function)
* [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)
* [label](../statements/label)
javascript SyntaxError: illegal character SyntaxError: illegal character
==============================
The JavaScript exception "illegal character" occurs when there is an invalid or unexpected token that doesn't belong at this position in the code.
Message
-------
```
SyntaxError: Invalid character (Edge)
SyntaxError: illegal character (Firefox)
SyntaxError: Invalid or unexpected token (Chrome)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
There is an invalid or unexpected token that doesn't belong at this position in the code. Use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign (`-`) versus a dash (`β`) or simple quotes (`"`) vs non-standard quotation marks (`"`).
Examples
--------
### Mismatched characters
Some characters look similar, but will cause the parser to fail interpreting your code. Famous examples of this are quotes, the minus or semicolon ([greek question mark (U+37e)](https://en.wikipedia.org/wiki/Question_mark#Greek_question_mark) looks same).
```
βThis looks like a stringβ; // SyntaxError: illegal character
// β and β are not " but look like this
42 β 13; // SyntaxError: illegal character
// β is not - but looks like this
const foo = 'bar'ΝΎ // SyntaxError: illegal character
// <37e> is not ; but looks like this
```
This should work:
```
"This is actually a string";
42 - 13;
const foo = 'bar';
```
Some editors and IDEs will notify you or at least use a slightly different highlighting for it, but not all. When something like this happens to your code and you're not able to find the source of the problem, it's often best to just delete the problematic line and retype it.
### Forgotten characters
It's easy to forget a character here or there.
```
const colors = ['#000', #333', '#666'];
// SyntaxError: illegal character
```
Add the missing quote for `'#333'`.
```
const colors = ['#000', '#333', '#666'];
```
### Hidden characters
When copy pasting code from external sources, there might be invalid characters. Watch out!
```
const foo = 'bar';β
// SyntaxError: illegal character
```
When inspecting this code in an editor like Vim, you can see that there is actually a [zero-width space (ZWSP) (U+200B)](https://en.wikipedia.org/wiki/Zero-width_space) character.
```
const foo = 'bar';<200b>
```
See also
--------
* [Lexical grammar](../lexical_grammar)
javascript TypeError: cyclic object value TypeError: cyclic object value
==============================
The JavaScript exception "cyclic object value" occurs when object references were found in [JSON](https://www.json.org/). [`JSON.stringify()`](../global_objects/json/stringify) doesn't try to solve them and fails accordingly.
Message
-------
```
TypeError: Converting circular structure to JSON (V8-based)
TypeError: cyclic object value (Firefox)
TypeError: JSON.stringify cannot serialize cyclic structures. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
The [JSON format](https://www.json.org/) per se doesn't support object references (although an [IETF draft exists](https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03)), hence [`JSON.stringify()`](../global_objects/json/stringify) doesn't try to solve them and fails accordingly.
Examples
--------
### Circular references
In a circular structure like the following
```
const circularReference = {otherData: 123};
circularReference.myself = circularReference;
```
[`JSON.stringify()`](../global_objects/json/stringify) will fail
```
JSON.stringify(circularReference);
// TypeError: cyclic object value
```
To serialize circular references you can use a library that supports them (e.g. [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/cycle.js)) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.
The snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the `replacer` parameter of [`JSON.stringify()`](../global_objects/json/stringify):
```
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(circularReference, getCircularReplacer());
// {"otherData":123}
```
See also
--------
* [`JSON.stringify`](../global_objects/json/stringify)
* [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/cycle.js) β Introduces two functions, `JSON.decycle` and `JSON.retrocycle`, which makes it possible to encode and decode cyclical structures and dags into an extended and retrocompatible JSON format.
| programming_docs |
javascript TypeError: "x" is not a constructor TypeError: "x" is not a constructor
===================================
The JavaScript exception "is not a constructor" occurs when there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor.
Message
-------
```
TypeError: x is not a constructor (V8-based & Firefox & Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
There was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. See [constructor](https://developer.mozilla.org/en-US/docs/Glossary/Constructor) or the [`new` operator](../operators/new) for more information on what a constructor is.
There are many global objects, like [`String`](../global_objects/string) or [`Array`](../global_objects/array), which are constructable using `new`. However, some global objects are not and their properties and methods are static. The following JavaScript standard built-in objects are not a constructor: [`Math`](../global_objects/math), [`JSON`](../global_objects/json), [`Symbol`](../global_objects/symbol), [`Reflect`](../global_objects/reflect), [`Intl`](../global_objects/intl), [`Atomics`](../global_objects/atomics).
[Generator functions](../statements/function*) cannot be used as constructors either.
Examples
--------
### Invalid cases
```
const Car = 1;
new Car();
// TypeError: Car is not a constructor
new Math();
// TypeError: Math is not a constructor
new Symbol();
// TypeError: Symbol is not a constructor
function\* f() {};
const obj = new f;
// TypeError: f is not a constructor
```
### A car constructor
Suppose you want to create an object type for cars. You want this type of object to be called `Car`, and you want it to have properties for make, model, and year. To do this, you would write the following function:
```
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);
```
### In Promises
When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a `new Promise(...)` and act on it. Instead, use the [`Promise.resolve()`](../global_objects/promise/resolve) or [`Promise.reject()`](../global_objects/promise/reject) [static methods](https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods).
This is not legal (the [`Promise` constructor](../global_objects/promise/promise) is not being called correctly) and will throw a `TypeError: this is not a constructor` exception:
```
const fn = () => {
return new Promise.resolve(true);
}
```
This is legal, but unnecessarily long:
```
const fn = () => {
return new Promise((resolve, reject) => {
resolve(true);
});
}
```
Instead, return the static method:
```
const resolveAlways = () => {
return Promise.resolve(true);
}
const rejectAlways = () => {
return Promise.reject(false);
}
```
See also
--------
* [constructor](https://developer.mozilla.org/en-US/docs/Glossary/Constructor)
* [`new` operator](../operators/new)
javascript SyntaxError: missing name after . operator SyntaxError: missing name after . operator
==========================================
The JavaScript exception "missing name after . operator" occurs when there is a problem with how the dot operator (`.`) is used for [property access](../operators/property_accessors).
Message
-------
```
SyntaxError: missing name after . operator (Firefox)
SyntaxError: Unexpected token '['. Expected a property name after '.'. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
The dot operator (`.`) is used for [property access](../operators/property_accessors). You will have to specify the name of the property that you want to access. For computed property access, you might need to change your property access from using a dot to using square brackets. These will allow you to compute an expression. Maybe you intended to do concatenation instead? A plus operator (`+`) is needed in that case. Please see the examples below.
Examples
--------
### Property access
[Property accessors](../operators/property_accessors) in JavaScript use either the dot (.) or square brackets (`[]`), but not both. Square brackets allow computed property access.
```
const obj = { foo: { bar: "baz", bar2: "baz2" } };
const i = 2;
obj.[foo].[bar]
// SyntaxError: missing name after . operator
obj.foo."bar"+i;
// SyntaxError: missing name after . operator
```
To fix this code, you need to access the object like this:
```
obj.foo.bar; // "baz"
// or alternatively
obj["foo"]["bar"]; // "baz"
// computed properties require square brackets
obj.foo["bar" + i]; // "baz2"
// or as template literal
obj.foo[`bar${i}`]; // "baz2"
```
### Property access vs. concatenation
If you are coming from another programming language (like [PHP](https://developer.mozilla.org/en-US/docs/Glossary/PHP)), it is also easy to mix up the dot operator (`.`) and the concatenation operator (`+`).
```
console.log("Hello" . "world");
// SyntaxError: missing name after . operator
```
Instead you need to use a plus sign for concatenation:
```
console.log("Hello" + "World");
```
See also
--------
* [Property accessors](../operators/property_accessors)
javascript ReferenceError: assignment to undeclared variable "x" ReferenceError: assignment to undeclared variable "x"
=====================================================
The JavaScript [strict mode](../strict_mode)-only exception "Assignment to undeclared variable" occurs when the value has been assigned to an undeclared variable.
Message
-------
```
ReferenceError: x is not defined (V8-based)
ReferenceError: assignment to undeclared variable x (Firefox)
ReferenceError: Can't find variable: x (Safari)
```
Error type
----------
[`ReferenceError`](../global_objects/referenceerror) in [strict mode](../strict_mode) only.
What went wrong?
----------------
A value has been assigned to an undeclared variable. In other words, there was an assignment without the `var` keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.
Three things to note about declared and undeclared variables:
* Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
* Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
* Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).
For more details and examples, see the [`var`](../statements/var) reference page.
Errors about undeclared variable assignments occur in [strict mode code](../strict_mode) only. In non-strict code, they are silently ignored.
Examples
--------
### Invalid cases
In this case, the variable "bar" is an undeclared variable.
```
function foo() {
'use strict';
bar = true;
}
foo(); // ReferenceError: assignment to undeclared variable bar
```
### Valid cases
To make "bar" a declared variable, you can add a [`let`](../statements/let), [`const`](../statements/var), or [`var`](../statements/var) keyword in front of it.
```
function foo() {
'use strict';
const bar = true;
}
foo();
```
See also
--------
* [Strict mode](../strict_mode)
javascript SyntaxError: missing ] after element list SyntaxError: missing ] after element list
=========================================
The JavaScript exception "missing ] after element list" occurs when there is an error with the array initializer syntax somewhere. Likely there is a closing bracket (`]`) or a comma (`,`) missing.
Message
-------
```
SyntaxError: missing ] after element list (Firefox)
SyntaxError: Unexpected token ';'. Expected either a closing ']' or a ',' following an array element. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
There is an error with the array initializer syntax somewhere. Likely there is a closing bracket (`]`) or a comma (`,`) missing.
Examples
--------
### Incomplete array initializer
```
const list = [1, 2,
const instruments = [
'Ukulele',
'Guitar',
'Piano'
};
const data = [{ foo: 'bar' } { bar: 'foo' }];
```
Correct would be:
```
const list = [1, 2];
const instruments = [
'Ukulele',
'Guitar',
'Piano'
];
const data = [{ foo: 'bar' }, { bar: 'foo' }];
```
See also
--------
* [`Array`](../global_objects/array)
javascript SyntaxError: a declaration in the head of a for-of loop can't have an initializer SyntaxError: a declaration in the head of a for-of loop can't have an initializer
=================================================================================
The JavaScript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a [for...of](../statements/for...of) loop contains an initializer expression such as `for (const i = 0 of iterable)`. This is not allowed in for-of loops.
Message
-------
```
SyntaxError: for-of loop variable declaration may not have an initializer. (V8-based)
SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)
SyntaxError: Cannot assign to the loop variable inside a for-of loop header. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
The head of a [for...of](../statements/for...of) loop contains an initializer expression. That is, a variable is declared and assigned a value `for (const i = 0 of iterable)`. This is not allowed in for-of loops. You might want a [`for`](../statements/for) loop that does allow an initializer.
Examples
--------
### Invalid for-of loop
```
const iterable = [10, 20, 30];
for (const value = 50 of iterable) {
console.log(value);
}
// SyntaxError: a declaration in the head of a for-of loop can't
// have an initializer
```
### Valid for-of loop
You need to remove the initializer (`value = 50`) in the head of the `for-of` loop. Maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example.
```
const iterable = [10, 20, 30];
for (let value of iterable) {
value += 50;
console.log(value);
}
// 60
// 70
// 80
```
See also
--------
* [`for...of`](../statements/for...of)
* [`for...in`](../statements/for...in) β disallows an initializer in strict mode as well ([SyntaxError: for-in loop head declarations may not have initializers](invalid_for-in_initializer))
* [`for`](../statements/for) β allows to define an initializer when iterating.
javascript RangeError: repeat count must be less than infinity RangeError: repeat count must be less than infinity
===================================================
The JavaScript exception "repeat count must be less than infinity" occurs when the [`String.prototype.repeat()`](../global_objects/string/repeat) method is used with a `count` argument that is infinity.
Message
-------
```
RangeError: Invalid string length (V8-based)
RangeError: Invalid count value: Infinity (V8-based)
RangeError: repeat count must be less than infinity and not overflow maximum string size (Firefox)
RangeError: Out of memory (Safari)
RangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror)What went wrong?
----------------
The [`String.prototype.repeat()`](../global_objects/string/repeat) method has been used. It has a `count` parameter indicating the number of times to repeat the string. It must be between 0 and less than positive [`Infinity`](../global_objects/infinity) and cannot be a negative number. The range of allowed values can be described like this: [0, +β).
The resulting string can also not be larger than the maximum string size, which can differ in JavaScript engines. In Firefox (SpiderMonkey) the maximum string size is 230 - 2 (~2GiB).
Examples
--------
### Invalid cases
```
'abc'.repeat(Infinity); // RangeError
'a'.repeat(2\*\*30); // RangeError
```
### Valid cases
```
'abc'.repeat(0); // ''
'abc'.repeat(1); // 'abc'
'abc'.repeat(2); // 'abcabc'
'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer)
```
See also
--------
* [`String.prototype.repeat()`](../global_objects/string/repeat)
javascript ReferenceError: "x" is not defined ReferenceError: "x" is not defined
==================================
The JavaScript exception "*variable* is not defined" occurs when there is a non-existent variable referenced somewhere.
Message
-------
```
ReferenceError: "x" is not defined (V8-based & Firefox)
ReferenceError: Can't find variable: x (Safari)
```
Error type
----------
[`ReferenceError`](../global_objects/referenceerror).
What went wrong?
----------------
There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or [scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope).
**Note:** When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as "$". Put the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element that loads the library before your code that uses it.
Examples
--------
### Variable not declared
```
foo.substring(1); // ReferenceError: foo is not defined
```
The "foo" variable isn't defined anywhere. It needs to be some string, so that the [`String.prototype.substring()`](../global_objects/string/substring) method will work.
```
const foo = 'bar';
foo.substring(1); // "ar"
```
### Wrong scope
A variable needs to be available in the current context of execution. Variables defined inside a [function](../functions) cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function
```
function numbers() {
const num1 = 2;
const num2 = 3;
return num1 + num2;
}
console.log(num1); // ReferenceError num1 is not defined.
```
However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope.
```
const num1 = 2;
const num2 = 3;
function numbers() {
return num1 + num2;
}
console.log(numbers()); // 5
```
See also
--------
* [Scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope)
* [Declaring variables in the JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declaring_variables)
* [Function scope in the JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#function_scope)
javascript SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
=============================================================================
The JavaScript [strict mode](../strict_mode)-only exception "0-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead" occurs when deprecated octal literals and octal escape sequences are used.
Message
-------
```
SyntaxError: Octal literals are not allowed in strict mode. (V8-based)
SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix instead (Firefox)
SyntaxError: Decimal integer literals with a leading zero are forbidden in strict mode (Safari)
SyntaxError: Octal escape sequences are not allowed in strict mode. (V8-based)
SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code (Firefox)
SyntaxError: The only valid numeric escape in strict mode is '\0' (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror) in [strict mode](../strict_mode) only.
What went wrong?
----------------
Octal literals and octal escape sequences are deprecated and will throw a [`SyntaxError`](../global_objects/syntaxerror) in strict mode. The standardized syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (`0o` or `0O`).
Examples
--------
### "0"-prefixed octal literals
```
"use strict";
03;
// SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix instead
```
### Octal escape sequences
```
"use strict";
"\251";
// SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
```
### Valid octal numbers
Use a leading zero followed by the letter "o" or "O":
```
0o3;
```
For octal escape sequences, you can use hexadecimal escape sequences instead:
```
'\xA9';
```
See also
--------
* [Lexical grammar](../lexical_grammar#octal)
* [Warning: 08/09 is not a legal ECMA-262 octal constant](bad_octal)
javascript RangeError: repeat count must be non-negative RangeError: repeat count must be non-negative
=============================================
The JavaScript exception "repeat count must be non-negative" occurs when the [`String.prototype.repeat()`](../global_objects/string/repeat) method is used with a `count` argument that is a negative number.
Message
-------
```
RangeError: Invalid count value: -1 (V8-based)
RangeError: repeat count must be non-negative (Firefox)
RangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror)What went wrong?
----------------
The [`String.prototype.repeat()`](../global_objects/string/repeat) method has been used. It has a `count` parameter indicating the number of times to repeat the string. It must be between 0 and less than positive [`Infinity`](../global_objects/infinity) and cannot be a negative number. The range of allowed values can be described like this: [0, +β).
Examples
--------
### Invalid cases
```
'abc'.repeat(-1); // RangeError
```
### Valid cases
```
'abc'.repeat(0); // ''
'abc'.repeat(1); // 'abc'
'abc'.repeat(2); // 'abcabc'
'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer)
```
See also
--------
* [`String.prototype.repeat()`](../global_objects/string/repeat)
javascript SyntaxError: missing = in const declaration SyntaxError: missing = in const declaration
===========================================
The JavaScript exception "missing = in const declaration" occurs when a const declaration was not given a value in the same statement (like `const RED_FLAG;`). You need to provide one (`const RED_FLAG = '#ff0'`).
Message
-------
```
SyntaxError: Missing initializer in const declaration (V8-based)
SyntaxError: missing = in const declaration (Firefox)
SyntaxError: Unexpected token ';'. const declared variable 'x' must have an initializer. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the [`const`](../statements/const) keyword. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later).
Examples
--------
### Missing const initializer
Unlike `var` or `let`, you must specify a value for a `const` declaration. This throws:
```
const COLUMNS;
// SyntaxError: missing = in const declaration
```
### Fixing the error
There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.
#### Adding a constant value
Specify the constant value in the same statement in which it's declared:
```
const COLUMNS = 80;
```
####
`const`, `let` or `var`?
Do not use `const` if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with [`let`](../statements/let) or global variable with [`var`](../statements/var). Both don't require an initial value.
```
let columns;
```
See also
--------
* [`const`](../statements/const)
* [`let`](../statements/let)
* [`var`](../statements/var)
| programming_docs |
javascript SyntaxError: missing ) after condition SyntaxError: missing ) after condition
======================================
The JavaScript exception "missing ) after condition" occurs when there is an error with how an [`if`](../statements/if...else) condition is written. It must appear in parenthesis after the `if` keyword.
Message
-------
```
SyntaxError: missing ) after condition (Firefox)
SyntaxError: Unexpected token '{'. Expected ')' to end an 'if' condition. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
There is an error with how an [`if`](../statements/if...else) condition is written. In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. The if statement executes a statement if a specified condition is truthy. In JavaScript, this condition must appear in parenthesis after the `if` keyword, like this:
```
if (condition) {
// do something if the condition is true
}
```
Examples
--------
### Missing parenthesis
It might just be an oversight, carefully check all you parenthesis in your code.
```
if (Math.PI < 3 {
console.log("wait what?");
}
// SyntaxError: missing ) after condition
```
To fix this code, you would need to add a parenthesis that closes the condition.
```
if (Math.PI < 3) {
console.log("wait what?");
}
```
### Misused is keyword
If you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in JavaScript.
```
if (done is true) {
console.log("we are done!");
}
// SyntaxError: missing ) after condition
```
Instead you need to use a correct [comparison operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). For example:
```
if (done === true) {
console.log("we are done!");
}
```
Or even better:
```
if (done) {
console.log("we are done!");
}
```
See also
--------
* [`if...else`](../statements/if...else)
* [Comparison operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators)
* [Making decisions in your code β conditionals](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)
javascript SyntaxError: identifier starts immediately after numeric literal SyntaxError: identifier starts immediately after numeric literal
================================================================
The JavaScript exception "identifier starts immediately after numeric literal" occurs when an identifier started with a digit. Identifiers can only start with a letter, underscore (\_), or dollar sign ($).
Message
-------
```
SyntaxError: Unexpected identifier after numeric literal (Edge)
SyntaxError: identifier starts immediately after numeric literal (Firefox)
SyntaxError: Unexpected number (Chrome)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
The names of variables, called [identifiers](https://developer.mozilla.org/en-US/docs/Glossary/Identifier), conform to certain rules, which your code must adhere to!
A JavaScript identifier must start with a letter, underscore (\_), or dollar sign ($). They can't start with a digit! Only subsequent characters can be digits (0-9).
Examples
--------
### Variable names starting with numeric literals
Variable names can't start with numbers in JavaScript. The following fails:
```
const 1life = 'foo';
// SyntaxError: identifier starts immediately after numeric literal
const foo = 1life;
// SyntaxError: identifier starts immediately after numeric literal
alert(1.foo);
// SyntaxError: identifier starts immediately after numeric literal
```
You will need to rename your variable to avoid the leading number.
```
const life1 = 'foo';
const foo = life1;
```
See also
--------
* [Lexical grammar](../lexical_grammar)
* [Variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables) in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
javascript TypeError: can't convert x to BigInt TypeError: can't convert x to BigInt
====================================
The JavaScript exception "x can't be converted to BigInt" occurs when attempting to convert a [`Symbol`](../global_objects/symbol), [`null`](../operators/null), or [`undefined`](../global_objects/undefined) value to a [`BigInt`](../global_objects/bigint), or if an operation expecting a BigInt parameter receives a number.
Message
-------
```
TypeError: Cannot convert null to a BigInt (V8-based)
TypeError: can't convert null to BigInt (Firefox)
TypeError: Invalid argument type in ToBigInt operation (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror).
What went wrong?
----------------
When using the [`BigInt()`](../global_objects/bigint/bigint) function to convert a value to a BigInt, the value would first be converted to a primitive. Then, if it's not one of BigInt, string, number, and boolean, the error is thrown.
Some operations, like [`BigInt.asIntN`](../global_objects/bigint/asintn), require the parameter to be a BigInt. Passing in a number in this case will also throw this error.
Examples
--------
### Using BigInt() on invalid values
```
const a = BigInt(null);
// TypeError: can't convert null to BigInt
const b = BigInt(undefined);
// TypeError: can't convert undefined to BigInt
const c = BigInt(Symbol("1"));
// TypeError: can't convert Symbol("1") to BigInt
```
```
const a = BigInt(1);
const b = BigInt(true);
const c = BigInt("1");
const d = BigInt(Symbol("1").description);
```
**Note:** Simply coercing the value to a string or number using [`String()`](../global_objects/string/string) or [`Number()`](../global_objects/number/number) before passing it to `BigInt()` is usually not sufficient to avoid all errors. If the string is not a valid integer number string, a [SyntaxError](invalid_bigint_syntax) is thrown; if the number is not an integer (most notably, [`NaN`](../global_objects/nan)), a [RangeError](cant_be_converted_to_bigint_because_it_isnt_an_integer) is thrown. If the range of input is unknown, properly validate it before using `BigInt()`.
### Passing a number to a function expecting a BigInt
```
const a = BigInt.asIntN(4, 8);
// TypeError: can't convert 8 to BigInt
const b = new BigInt64Array(3).fill(3);
// TypeError: can't convert 3 to BigInt
```
```
const a = BigInt.asIntN(4, 8n);
const b = new BigInt64Array(3).fill(3n);
```
See also
--------
* [`BigInt()`](../global_objects/bigint/bigint)
javascript RangeError: BigInt division by zero RangeError: BigInt division by zero
===================================
The JavaScript exception "BigInt division by zero" occurs when a [`BigInt`](../global_objects/bigint) is divided by `0n`.
Message
-------
```
RangeError: Division by zero (V8-based)
RangeError: BigInt division by zero (Firefox)
RangeError: 0 is an invalid divisor value. (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror).
What went wrong?
----------------
The divisor of a [division](../operators/division) or [remainder](../operators/remainder) operator is `0n`. In [`Number`](../global_objects/number) arithmetic, this produces [`Infinity`](../global_objects/infinity), but there's no "infinity value" in BigInts, so an error is issued. Check if the divisor is `0n` before doing the division.
Examples
--------
### Division by 0n
```
const a = 1n;
const b = 0n;
const quotient = a / b;
// RangeError: BigInt division by zero
```
Instead, check if the divisor is `0n` first, and either issue an error with a better message, or fallback to a different value, like `Infinity` or `undefined`.
```
const a = 1n;
const b = 0n;
const quotient = b === 0n ? undefined : a / b;
```
See also
--------
* [`BigInt`](../global_objects/bigint)
* [Division](../operators/division)
* [Remainder](../operators/remainder)
javascript TypeError: cannot use 'in' operator to search for 'x' in 'y' TypeError: cannot use 'in' operator to search for 'x' in 'y'
============================================================
The JavaScript exception "right-hand side of 'in' should be an object" occurs when the [`in` operator](../operators/in) was used to search in strings, or in numbers, or other primitive types. It can only be used to check if a property is in an object.
Message
-------
```
TypeError: Cannot use 'in' operator to search for 'x' in 'y' (V8-based & Firefox)
TypeError: right-hand side of 'in' should be an object, got null (Firefox)
TypeError: "y" is not an Object. (evaluating '"x" in "y"') (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
The [`in` operator](../operators/in) can only be used to check if a property is in an object. You can't search in strings, or in numbers, or other primitive types.
Examples
--------
### Searching in strings
Unlike in other programming languages (e.g. Python), you can't search in strings using the [`in` operator](../operators/in).
```
"Hello" in "Hello World";
// TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World'
```
Instead you will need to use [`String.prototype.includes()`](../global_objects/string/includes), for example.
```
"Hello World".includes("Hello");
// true
```
### The operand can't be null or undefined
Make sure the object you are inspecting isn't actually [`null`](../operators/null) or [`undefined`](../global_objects/undefined).
```
const foo = null;
"bar" in foo;
// TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome)
// TypeError: right-hand side of 'in' should be an object, got null (Firefox)
```
The `in` operator always expects an object.
```
const foo = { baz: "bar" };
"bar" in foo; // false
"PI" in Math; // true
"pi" in Math; // false
```
### Searching in arrays
Be careful when using the `in` operator to search in [`Array`](../global_objects/array) objects. The `in` operator checks the index number, not the value at that index.
```
const trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
3 in trees; // true
"oak" in trees; // false
```
See also
--------
* [`in` operator](../operators/in)
javascript SyntaxError: missing } after property list SyntaxError: missing } after property list
==========================================
The JavaScript exception "missing } after property list" occurs when there is a mistake in the [object initializer](../operators/object_initializer) syntax somewhere. Might be in fact a missing curly bracket, but could also be a missing comma.
Message
-------
```
SyntaxError: missing } after property list (Firefox)
SyntaxError: Unexpected identifier 'c'. Expected '}' to end an object literal. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
There is a mistake in the [object initializer](../operators/object_initializer) syntax somewhere. Might be in fact a missing curly bracket, but could also be a missing comma, for example. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle.
Examples
--------
### Forgotten comma
Oftentimes, there is a missing comma in your object initializer code:
```
const obj = {
a: 1,
b: { myProp: 2 }
c: 3
};
```
Correct would be:
```
const obj = {
a: 1,
b: { myProp: 2 },
c: 3
};
```
See also
--------
* [Object initializer](../operators/object_initializer)
javascript SyntaxError: test for equality (==) mistyped as assignment (=)? SyntaxError: test for equality (==) mistyped as assignment (=)?
===============================================================
The JavaScript warning "test for equality (==) mistyped as assignment (=)?" occurs when there was an assignment (`=`) when you would normally expect a test for equality (`==`).
Message
-------
```
Warning: SyntaxError: test for equality (==) mistyped as assignment (=)?
```
Error type
----------
(Firefox only) [`SyntaxError`](../global_objects/syntaxerror) warning which is reported only if `javascript.options.strict` preference is set to `true`.
What went wrong?
----------------
There was an assignment (`=`) when you would normally expect a test for equality (`==`). To help debugging, JavaScript (with strict warnings enabled) warns about this pattern.
Examples
--------
### Assignment within conditional expressions
It is advisable to not use simple assignments in a conditional expression (such as [`if...else`](../statements/if...else)), because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
```
if (x = y) {
// do the right thing
}
```
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
```
if ((x = y)) {
// do the right thing
}
```
Otherwise, you probably meant to use a comparison operator (e.g. `==` or `===`):
```
if (x === y) {
// do the right thing
}
```
See also
--------
* [`if...else`](../statements/if...else)
* [Equality operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators)
javascript Warning: -file- is being assigned a //# sourceMappingURL, but already has one Warning: -file- is being assigned a //# sourceMappingURL, but already has one
=============================================================================
The JavaScript warning "-file- is being assigned a //# sourceMappingURL, but already has one." occurs when a source map has been specified more than once for a given JavaScript source.
Message
-------
```
Warning: -file- is being assigned a //# sourceMappingURL, but already has one.
```
Error type
----------
A warning. JavaScript execution won't be halted.
What went wrong?
----------------
A source map has been specified more than once for a given JavaScript source.
JavaScript sources are often combined and minified to make delivering them from the server more efficient. With [source maps](https://developer.chrome.com/blog/sourcemaps/), the debugger can map the code being executed to the original source files. There are two ways to assign a source map, either by using a comment or by setting a header to the JavaScript file.
Examples
--------
### Setting source maps
Setting a source map by using a comment in the file:
```
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```
Or, alternatively, you can set a header to your JavaScript file:
```
X-SourceMap: /path/to/file.js.map
```
See also
--------
* [How to use a source map β Firefox Tools documentation](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html)
* [Introduction to source maps (2012)](https://developer.chrome.com/blog/sourcemaps/)
javascript TypeError: invalid assignment to const "x" TypeError: invalid assignment to const "x"
==========================================
The JavaScript exception "invalid assignment to const" occurs when it was attempted to alter a constant value. JavaScript [`const`](../statements/const) declarations can't be re-assigned or redeclared.
Message
-------
```
TypeError: Assignment to constant variable. (V8-based)
TypeError: invalid assignment to const 'x' (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the [`const`](../statements/const) keyword.
Examples
--------
### Invalid redeclaration
Assigning a value to the same constant name in the same block-scope will throw.
```
const COLUMNS = 80;
// β¦
COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS'
```
### Fixing the error
There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.
#### Rename
If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope.
```
const COLUMNS = 80;
const WIDE\_COLUMNS = 120;
```
#### const, let or var?
Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with [`let`](../statements/let) or global variable with [`var`](../statements/var).
```
let columns = 80;
// β¦
columns = 120;
```
#### Scoping
Check if you are in the correct scope. Should this constant appear in this scope or was it meant to appear in a function, for example?
```
const COLUMNS = 80;
function setupBigScreenEnvironment() {
const COLUMNS = 120;
}
```
### const and immutability
The `const` declaration creates a read-only reference to a value. It does **not** mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable:
```
const obj = {foo: 'bar'};
obj = {foo: 'baz'}; // TypeError: invalid assignment to const `obj'
```
But you can mutate the properties in a variable:
```
obj.foo = 'baz';
obj; // { foo: "baz" }
```
See also
--------
* [`const`](../statements/const)
* [`let`](../statements/let)
* [`var`](../statements/var)
javascript URIError: malformed URI sequence URIError: malformed URI sequence
================================
The JavaScript exception "malformed URI sequence" occurs when URI encoding or decoding wasn't successful.
Message
-------
```
URIError: URI malformed (V8-based)
URIError: malformed URI sequence (Firefox)
URIError: String contained an illegal UTF-16 sequence. (Safari)
```
Error type
----------
[`URIError`](../global_objects/urierror)What went wrong?
----------------
URI encoding or decoding wasn't successful. An argument given to either the [`decodeURI`](../global_objects/decodeuri), [`encodeURI`](../global_objects/encodeuri), [`encodeURIComponent`](../global_objects/encodeuricomponent), or [`decodeURIComponent`](../global_objects/decodeuricomponent) function was not valid, so that the function was unable encode or decode properly.
Examples
--------
### Encoding
Encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. An [`URIError`](../global_objects/urierror) will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example:
```
encodeURI('\uD800');
// "URIError: malformed URI sequence"
encodeURI('\uDFFF');
// "URIError: malformed URI sequence"
```
A high-low pair is OK. For example:
```
encodeURI('\uD800\uDFFF');
// "%F0%90%8F%BF"
```
### Decoding
Decoding replaces each escape sequence in the encoded URI component with the character that it represents. If there isn't such a character, an error will be thrown:
```
decodeURIComponent('%E0%A4%A');
// "URIError: malformed URI sequence"
```
With proper input, this should usually look like something like this:
```
decodeURIComponent('JavaScript\_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
// "JavaScript\_ΡΠ΅Π»Π»Ρ"
```
See also
--------
* [`URIError`](../global_objects/urierror)
* [`decodeURI`](../global_objects/decodeuri)
* [`encodeURI`](../global_objects/encodeuri)
* [`encodeURIComponent`](../global_objects/encodeuricomponent)
* [`decodeURIComponent`](../global_objects/decodeuricomponent)
| programming_docs |
javascript RangeError: x can't be converted to BigInt because it isn't an integer RangeError: x can't be converted to BigInt because it isn't an integer
======================================================================
The JavaScript exception "x can't be converted to BigInt because it isn't an integer" occurs when the [`BigInt()`](../global_objects/bigint/bigint) function is used on a number that isn't an integer.
Message
-------
```
RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer (V8-based & Firefox)
RangeError: Not an integer (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror).
What went wrong?
----------------
When using the [`BigInt()`](../global_objects/bigint/bigint) function to convert a number to a BigInt, the number must be an integer (such that [`Number.isInteger`](../global_objects/number/isinteger) returns true).
Examples
--------
### Invalid cases
```
const a = BigInt(1.5);
// RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer
const b = BigInt(NaN);
// RangeError: NaN cannot be converted to a BigInt because it is not an integer
```
### Valid cases
```
const a = BigInt(1);
```
See also
--------
* [`BigInt()`](../global_objects/bigint/bigint)
* [`Number.isInteger`](../global_objects/number/isinteger)
javascript RangeError: invalid array length RangeError: invalid array length
================================
The JavaScript exception "Invalid array length" occurs when specifying an array length that is either negative, a floating number or exceeds the maximum supported by the platform (i.e. when creating an [`Array`](../global_objects/array) or [`ArrayBuffer`](../global_objects/arraybuffer), or when setting the [`length`](../global_objects/array/length) property).
The maximum allowed array length depends on the platform, browser and browser version. For [`Array`](../global_objects/array) the maximum length is 232-1. For [`ArrayBuffer`](../global_objects/arraybuffer) the maximum is 231-1 (2GiB-1) on 32-bit systems. From Firefox version 89 the maximum value of [`ArrayBuffer`](../global_objects/arraybuffer) is 233 (8GiB) on 64-bit systems.
**Note:** `Array` and `ArrayBuffer` are independent data structures (the implementation of one does not affect the other).
Message
-------
```
RangeError: invalid array length (V8-based & Firefox)
RangeError: Array buffer allocation failed (V8-based)
RangeError: Array size is not a small enough positive integer. (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror)What went wrong?
----------------
An invalid array length might appear in these situations:
* Creating an [`Array`](../global_objects/array) or [`ArrayBuffer`](../global_objects/arraybuffer) with a negative length, or setting a negative value for the [`length`](../global_objects/array/length) property.
* Creating an [`Array`](../global_objects/array) or setting the [`length`](../global_objects/array/length) property greater than 232-1.
* Creating an [`ArrayBuffer`](../global_objects/arraybuffer) that is bigger than 232-1 (2GiB-1) on a 32-bit system, or 233 (8GiB) on a 64-bit system.
* Creating an [`Array`](../global_objects/array) or setting the [`length`](../global_objects/array/length) property to a floating-point number.
* Before Firefox 89: Creating an [`ArrayBuffer`](../global_objects/arraybuffer) that is bigger than 232-1 (2GiB-1).
If you are creating an `Array`, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the `Array`.
Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor.
Examples
--------
### Invalid cases
```
new Array(Math.pow(2, 40))
new Array(-1)
new ArrayBuffer(Math.pow(2, 32)) // 32-bit system
new ArrayBuffer(-1)
const a = [];
a.length = a.length - 1; // set the length property to -1
const b = new Array(Math.pow(2, 32) - 1);
b.length = b.length + 1; // set the length property to 2^32
b.length = 2.5; // set the length property to a floating-point number
const c = new Array(2.5); // pass a floating-point number
```
### Valid cases
```
[ Math.pow(2, 40) ] // [ 1099511627776 ]
[ -1 ] // [ -1 ]
new ArrayBuffer(Math.pow(2, 32) - 1)
new ArrayBuffer(Math.pow(2, 33)) // 64-bit systems after Firefox 89
new ArrayBuffer(0)
const a = [];
a.length = Math.max(0, a.length - 1);
const b = new Array(Math.pow(2, 32) - 1);
b.length = Math.min(0xffffffff, b.length + 1);
// 0xffffffff is the hexadecimal notation for 2^32 - 1
// which can also be written as (-1 >>> 0)
b.length = 3;
const c = new Array(3);
```
See also
--------
* [`Array`](../global_objects/array)
* [`length`](../global_objects/array/length)
* [`ArrayBuffer`](../global_objects/arraybuffer)
javascript RangeError: argument is not a valid code point RangeError: argument is not a valid code point
==============================================
The JavaScript exception "Invalid code point" occurs when [`NaN`](../global_objects/nan) values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111) are used with [`String.fromCodePoint()`](../global_objects/string/fromcodepoint).
Message
-------
```
RangeError: Invalid code point -1 (V8-based)
RangeError: -1 is not a valid code point (Firefox)
RangeError: Arguments contain a value that is out of range of code points (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror)What went wrong?
----------------
[`String.fromCodePoint()`](../global_objects/string/fromcodepoint) throws this error when passed [`NaN`](../global_objects/nan) values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111).
A [code point](https://en.wikipedia.org/wiki/Code_point) is a value in the Unicode codespace; that is, the range of integers from `0` to `0x10FFFF`.
Examples
--------
### Invalid cases
```
String.fromCodePoint('\_'); // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1); // RangeError
String.fromCodePoint(3.14); // RangeError
String.fromCodePoint(3e-2); // RangeError
String.fromCodePoint(NaN); // RangeError
```
### Valid cases
```
String.fromCodePoint(42); // "\*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404"
String.fromCodePoint(0x2F804); // "\uD87E\uDC04"
String.fromCodePoint(194564); // "\uD87E\uDC04"
String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
```
See also
--------
* [`String.fromCodePoint()`](../global_objects/string/fromcodepoint)
javascript TypeError: invalid 'instanceof' operand 'x' TypeError: invalid 'instanceof' operand 'x'
===========================================
The JavaScript exception "invalid 'instanceof' operand" occurs when the right-hand side operands of the [`instanceof` operator](../operators/instanceof) isn't used with a constructor object, i.e. an object which has a `prototype` property and is callable.
Message
-------
```
TypeError: Right-hand side of 'instanceof' is not an object (V8-based)
TypeError: Right-hand side of 'instanceof' is not callable (V8-based)
TypeError: invalid 'instanceof' operand "x" (Firefox)
TypeError: ({}) is not a function (Firefox)
TypeError: Right hand side of instanceof is not an object (Safari)
TypeError: {} is not a function. (evaluating '"x" instanceof {}') (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
The [`instanceof` operator](../operators/instanceof) expects the right-hand-side operands to be a constructor object, i.e. an object which has a `prototype` property and is callable. It can also be an object with a [`Symbol.hasInstance`](../global_objects/symbol/hasinstance) method.
Examples
--------
### instanceof vs typeof
```
"test" instanceof ""; // TypeError: invalid 'instanceof' operand ""
42 instanceof 0; // TypeError: invalid 'instanceof' operand 0
function Foo() {}
const f = Foo(); // Foo() is called and returns undefined
const x = new Foo();
x instanceof f; // TypeError: invalid 'instanceof' operand f
x instanceof x; // TypeError: x is not a function
```
To fix these errors, you will either need to replace the [`instanceof` operator](../operators/instanceof) with the [`typeof` operator](../operators/typeof), or to make sure you use the function name, instead of the result of its evaluation.
```
typeof "test" === "string"; // true
typeof 42 === "number" // true
function Foo() {}
const f = Foo; // Do not call Foo.
const x = new Foo();
x instanceof f; // true
x instanceof Foo; // true
```
See also
--------
* [`instanceof` operator](../operators/instanceof)
* [`typeof` operator](../operators/typeof)
javascript SyntaxError: missing variable name SyntaxError: missing variable name
==================================
The JavaScript exception "missing variable name" is a common error. It is usually caused by omitting a variable name or a typographic error.
Message
-------
```
SyntaxError: missing variable name (Firefox)
SyntaxError: Unexpected token '='. Expected a parameter pattern or a ')' in parameter list. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
A variable is missing a name. The cause is most likely a typo or a forgotten variable name. Make sure that you've provided the name of the variable before the `=` sign.
When declaring multiple variables at the same time, make sure that the previous lines/declaration does not end with a comma instead of a semicolon.
Examples
--------
### Missing a variable name
```
const = "foo";
```
It is easy to forget to assign a name for your variable!
```
const description = "foo";
```
### Reserved keywords can't be variable names
There are a few variable names that are [reserved keywords](../lexical_grammar#keywords). You can't use these. Sorry :(
```
const debugger = "whoop";
// SyntaxError: missing variable name
```
### Declaring multiple variables
Pay special attention to commas when declaring multiple variables. Is there an excess comma, or did you use commas instead of semicolons? Did you remember to assign values for all your `const` variables?
```
let x, y = "foo",
const z, = "foo"
const first = document.getElementById('one'),
const second = document.getElementById('two'),
// SyntaxError: missing variable name
```
The fixed version:
```
let x, y = "foo";
const z = "foo";
const first = document.getElementById('one');
const second = document.getElementById('two');
```
### Arrays
[`Array`](../global_objects/array) literals in JavaScript need square brackets around the values. This won't work:
```
const arr = 1,2,3,4,5;
// SyntaxError: missing variable name
```
This would be correct:
```
const arr = [1,2,3,4,5];
```
See also
--------
* [Good variable names](https://wiki.c2.com/?GoodVariableNames)
* [`var`](../statements/var)
* [Variable declarations in the JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declarations)
javascript Warning: expression closures are deprecated Warning: expression closures are deprecated
===========================================
The JavaScript warning "expression closures are deprecated" occurs when the non-standard expression closure syntax (shorthand function syntax) is used. This syntax is now removed and the warning message is obsolete.
Message
-------
```
Warning: expression closures are deprecated
```
Error type
----------
Warning. JavaScript execution won't be halted.
What went wrong?
----------------
The non-standard expression closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. This syntax has been removed entirely in [bug 1083458](https://bugzilla.mozilla.org/show_bug.cgi?id=1083458) and scripts using it will throw a [`SyntaxError`](../global_objects/syntaxerror) in newer versions of Firefox.
Examples
--------
### Deprecated syntax
Expression closures omit curly braces or return statements from function declarations or from method definitions in objects.
```
var x = function () 1;
var obj = {
count: function () 1
};
```
### Standard syntax
To convert the non-standard expression closures syntax to standard ECMAScript syntax, you can add curly braces and return statements.
```
const x = function () { return 1; }
const obj = {
count() { return 1; }
};
```
### Standard syntax using arrow functions
Alternatively, you can use [arrow functions](../functions/arrow_functions):
```
const x = () => 1;
```
### Standard syntax using shorthand method syntax
Expression closures can also be found with getter and setter, like this:
```
var obj = {
get x() 1,
set x(v) this.v = v
};
```
With [method definitions](../functions/method_definitions), this can be converted to:
```
const obj = {
get x() { return 1 },
set x(v) { this.v = v }
};
```
See also
--------
* [Arrow functions](../functions/arrow_functions)
* [Method definitions](../functions/method_definitions)
javascript SyntaxError: unterminated string literal SyntaxError: unterminated string literal
========================================
The JavaScript error "unterminated string literal" occurs when there is an unterminated [string literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#string_literals) somewhere. String literals must be enclosed by single (`'`) or double (`"`) quotes.
Message
-------
```
SyntaxError: Unterminated string constant (Edge)
SyntaxError: unterminated string literal (Firefox)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
There is an unterminated [string literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#string_literals) somewhere. String literals must be enclosed by single (`'`) or double (`"`) quotes. JavaScript makes no distinction between single-quoted strings and double-quoted strings. [Escape sequences](../global_objects/string#escape_sequences) work in strings created with either single or double quotes. To fix this error, check if:
* you have opening and closing quotes (single or double) for your string literal,
* you have escaped your string literal correctly,
* your string literal isn't split across multiple lines.
Examples
--------
### Multiple lines
You can't split a string across multiple lines like this in JavaScript:
```
const longString = 'This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.';
// SyntaxError: unterminated string literal
```
Instead, use the [+ operator](../operators/addition), a backslash, or [template literals](../template_literals). The `+` operator variant looks 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. That form looks like this:
```
const longString = 'This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.';
```
Another possibility is to use [template literals](../template_literals).
```
const longString = `This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.`;
```
See also
--------
* [string literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#string_literals)
* [Template literals](../template_literals)
javascript TypeError: "x" is not a non-null object TypeError: "x" is not a non-null object
=======================================
The JavaScript exception "is not a non-null object" occurs when an object is expected somewhere and wasn't provided. [`null`](../operators/null) is not an object and won't work.
Message
-------
```
TypeError: Property description must be an object: x (V8-based)
TypeError: Property descriptor must be an object, got "x" (Firefox)
TypeError: Property description must be an object. (Safari)
TypeError: Invalid value used in weak set (V8-based)
TypeError: WeakSet value must be an object, got "x" (Firefox)
TypeError: Attempted to add a non-object value to a WeakSet (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
An object is expected somewhere and wasn't provided. [`null`](../operators/null) is not an object and won't work. You must provide a proper object in the given situation.
Examples
--------
### Property descriptor expected
When methods like [`Object.create()`](../global_objects/object/create) or [`Object.defineProperty()`](../global_objects/object/defineproperty) and [`Object.defineProperties()`](../global_objects/object/defineproperties) are used, the optional descriptor parameter expects a property descriptor object. Providing no object (like just a number), will throw an error:
```
Object.defineProperty({}, 'key', 1);
// TypeError: 1 is not a non-null object
Object.defineProperty({}, 'key', null);
// TypeError: null is not a non-null object
```
A valid property descriptor object might look like this:
```
Object.defineProperty({}, 'key', { value: 'foo', writable: false });
```
### WeakMap and WeakSet objects require object keys
[`WeakMap`](../global_objects/weakmap) and [`WeakSet`](../global_objects/weakset) objects store object keys. You can't use other types as keys.
```
const ws = new WeakSet();
ws.add('foo');
// TypeError: "foo" is not a non-null object
```
Use objects instead:
```
ws.add({ foo: 'bar' });
ws.add(window);
```
See also
--------
* [`Object.create()`](../global_objects/object/create)
* [`Object.defineProperty()`](../global_objects/object/defineproperty), [`Object.defineProperties()`](../global_objects/object/defineproperties)
* [`WeakMap`](../global_objects/weakmap), [`WeakSet`](../global_objects/weakset)
javascript SyntaxError: Unexpected token SyntaxError: Unexpected token
=============================
The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.
Message
-------
```
SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
A specific language construct was expected, but something else was provided. This might be a simple typo.
Examples
--------
### Expression expected
For example, when chaining expressions, trailing commas are not allowed.
```
for (let i = 0; i < 5,; ++i) {
console.log(i);
}
// Uncaught SyntaxError: expected expression, got ';'
```
Correct would be omitting the comma or adding another expression:
```
for (let i = 0; i < 5; ++i) {
console.log(i);
}
```
### Not enough brackets
Sometimes, you leave out brackets around `if` statements:
```
function round(n, upperBound, lowerBound) {
if (n > upperBound) || (n < lowerBound) { // Not enough brackets here!
throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
} else if (n < (upperBound + lowerBound) / 2) {
return lowerBound;
} else {
return upperBound;
}
} // SyntaxError: expected expression, got '||'
```
The brackets may look correct at first, but note how the `||` is outside the brackets. Correct would be putting brackets around the `||`:
```
function round(n, upperBound, lowerBound) {
if ((n > upperBound) || (n < lowerBound)) {
throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
} else if (n < (upperBound + lowerBound) / 2) {
return lowerBound;
} else {
return upperBound;
}
}
```
See also
--------
* [`SyntaxError`](../global_objects/syntaxerror)
| programming_docs |
javascript TypeError: can't delete non-configurable array element TypeError: can't delete non-configurable array element
======================================================
The JavaScript exception "can't delete non-configurable array element" occurs when it was attempted to [shorten the length](../global_objects/array/length#shortening_an_array) of an array, but one of the array's elements is [non-configurable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties).
Message
-------
```
TypeError: Cannot delete property '1' of [object Array] (V8-based)
TypeError: can't delete non-configurable array element (Firefox)
TypeError: Unable to delete property. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
It was attempted to [shorten the length](../global_objects/array/length#shortening_an_array) of an array, but one of the array's elements is [non-configurable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties). When shortening an array, the elements beyond the new array length will be deleted, which failed in this situation.
The `configurable` attribute controls whether the property can be deleted from the object and whether its attributes (other than `writable`) can be changed.
Usually, properties in an object created by an [array initializer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) are configurable. However, for example, when using [`Object.defineProperty()`](../global_objects/object/defineproperty), the property isn't configurable by default.
Examples
--------
### Non-configurable properties created by Object.defineProperty
The [`Object.defineProperty()`](../global_objects/object/defineproperty) creates non-configurable properties by default if you haven't specified them as configurable.
```
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0 });
Object.defineProperty(arr, 1, { value: "1" });
arr.length = 1;
// TypeError: can't delete non-configurable array element
```
You will need to set the elements as configurable, if you intend to shorten the array.
```
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0, configurable: true });
Object.defineProperty(arr, 1, { value: "1", configurable: true });
arr.length = 1;
```
### Sealed Arrays
The [`Object.seal()`](../global_objects/object/seal) function marks all existing elements as non-configurable.
```
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);
arr.length = 1;
// TypeError: can't delete non-configurable array element
```
You either need to remove the [`Object.seal()`](../global_objects/object/seal) call, or make a copy of it. In case of a copy, shortening the copy of the array does not modify the original array length.
```
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);
// Copy the initial array to shorten the copy
const copy = Array.from(arr);
copy.length = 1;
// arr.length === 3
```
See also
--------
* [[[Configurable]]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties)
* [`length`](../global_objects/array/length)
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
* [`Object.seal()`](../global_objects/object/seal)
javascript TypeError: X.prototype.y called on incompatible type TypeError: X.prototype.y called on incompatible type
====================================================
The JavaScript exception "called on incompatible target (or object)" occurs when a function (on a given object), is called with a `this` not corresponding to the type expected by the function.
Message
-------
```
TypeError: Method Set.prototype.add called on incompatible receiver undefined (V8-based)
TypeError: Bind must be called on a function (V8-based)
TypeError: Function.prototype.toString called on incompatible object (Firefox)
TypeError: Function.prototype.bind called on incompatible target (Firefox)
TypeError: Type error (Safari)
TypeError: undefined is not an object (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
When this error is thrown, a function (on a given object), is called with a `this` not corresponding to the type expected by the function.
This issue can arise when using the [`Function.prototype.call()`](../global_objects/function/call) or [`Function.prototype.apply()`](../global_objects/function/apply) methods, and providing a `this` argument which does not have the expected type.
This issue can also happen when providing a function that is stored as a property of an object as an argument to another function. In this case, the object that stores the function won't be the `this` target of that function when it is called by the other function. To work-around this issue, you will either need to provide a lambda which is making the call, or use the [`Function.prototype.bind()`](../global_objects/function/bind) function to force the `this` argument to the expected object.
Examples
--------
### Invalid cases
```
const mySet = new Set;
['bar', 'baz'].forEach(mySet.add);
// mySet.add is a function, but "mySet" is not captured as this.
const myFun = function () {
console.log(this);
};
['bar', 'baz'].forEach(myFun.bind);
// myFun.bind is a function, but "myFun" is not captured as this.
```
### Valid cases
```
const mySet = new Set;
['bar', 'baz'].forEach(mySet.add.bind(mySet));
// This works due to binding "mySet" as this.
const myFun = function () {
console.log(this);
};
['bar', 'baz'].forEach((x) => myFun.bind(x));
// This works using the "bind" function. It creates a lambda forwarding the argument.
```
See also
--------
* [`Function.prototype.call()`](../global_objects/function/call)
* [`Function.prototype.apply()`](../global_objects/function/apply)
* [`Function.prototype.bind()`](../global_objects/function/bind)
javascript TypeError: 'x' is not iterable TypeError: 'x' is not iterable
==============================
The JavaScript exception "is not iterable" occurs when the value which is given as the right-hand side of [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement), as argument of a function such as [`Promise.all`](../global_objects/promise/all) or [`TypedArray.from`](../global_objects/typedarray/from), or as the right-hand side of an array [destructuring assignment](../operators/destructuring_assignment), is not an [iterable object](../iteration_protocols).
Message
-------
```
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) (V8-based)
TypeError: x is not iterable (Firefox)
TypeError: undefined is not a function (near '...[x]...') (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
The value which is given as the right-hand side of [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement), or as argument of a function such as [`Promise.all`](../global_objects/promise/all) or [`TypedArray.from`](../global_objects/typedarray/from), or as the right-hand side of an array [destructuring assignment](../operators/destructuring_assignment), is not an [iterable object](../iteration_protocols). An iterable can be a built-in iterable type such as [`Array`](../global_objects/array), [`String`](../global_objects/string) or [`Map`](../global_objects/map), a generator result, or an object implementing the [iterable protocol](../iteration_protocols#the_iterable_protocol).
Examples
--------
### Array destructuring a non-iterable
```
const myobj = { arrayOrObjProp1: {}, arrayOrObjProp2: [42] };
const { arrayOrObjProp1: [value1], arrayOrObjProp2: [value2] } = myobj; // TypeError: object is not iterable
console.log(value1, value2);
```
The non-iterable might turn to be `undefined` in some runtime environments.
### Iterating over Object properties
In JavaScript, [`Object`](../global_objects/object)s are not iterable unless they implement the [iterable protocol](../iteration_protocols#the_iterable_protocol). Therefore, you cannot use [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) to iterate over the properties of an object.
```
const obj = { France: 'Paris', England: 'London' };
for (const p of obj) { // TypeError: obj is not iterable
// β¦
}
```
Instead you have to use [`Object.keys`](../global_objects/object/keys) or [`Object.entries`](../global_objects/object/entries), to iterate over the properties or entries of an object.
```
const obj = { France: 'Paris', England: 'London' };
// Iterate over the property names:
for (const country of Object.keys(obj)) {
const capital = obj[country];
console.log(country, capital);
}
for (const [country, capital] of Object.entries(obj)) {
console.log(country, capital);
}
```
Another option for this use case might be to use a [`Map`](../global_objects/map):
```
const map = new Map;
map.set('France', 'Paris');
map.set('England', 'London');
// Iterate over the property names:
for (const country of map.keys()) {
const capital = map.get(country);
console.log(country, capital);
}
for (const capital of map.values()) {
console.log(capital);
}
for (const [country, capital] of map.entries()) {
console.log(country, capital);
}
```
### Iterating over a generator
[Generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#generator_functions) are functions you call to produce an iterable object.
```
function\* generate(a, b) {
yield a;
yield b;
}
for (const x of generate) { // TypeError: generate is not iterable
console.log(x);
}
```
When they are not called, the [`Function`](../global_objects/function) object corresponding to the generator is callable, but not iterable. Calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator.
```
function\* generate(a, b) {
yield a;
yield b;
}
for (const x of generate(1, 2)) {
console.log(x);
}
```
### Iterating over a custom iterable
Custom iterables can be created by implementing the [`Symbol.iterator`](../global_objects/symbol/iterator) method. You must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method.
```
const myEmptyIterable = {
[Symbol.iterator]() {
return []; // [] is iterable, but it is not an iterator β it has no next method.
}
}
Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable
```
Here is a correct implementation:
```
const myEmptyIterable = {
[Symbol.iterator]() {
return [][Symbol.iterator]()
}
}
Array.from(myEmptyIterable); // []
```
See also
--------
* [Iterable protocol](../iteration_protocols#the_iterable_protocol)
* [`Object.keys`](../global_objects/object/keys)
* [`Object.entries`](../global_objects/object/entries)
* [`Map`](../global_objects/map)
* [Generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#generator_functions)
* [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement)
javascript SyntaxError: invalid assignment left-hand side SyntaxError: invalid assignment left-hand side
==============================================
The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single `=` sign was used instead of `==` or `===`.
Message
-------
```
SyntaxError: Invalid left-hand side in assignment (V8-based)
SyntaxError: invalid assignment left-hand side (Firefox)
SyntaxError: Left side of assignment is not a reference. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
There was an unexpected assignment somewhere. This might be due to a mismatch of an [assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators) and an [equality operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators), for example. While a single `=` sign assigns a value to a variable, the `==` or `===` operators compare a value.
Examples
--------
### Typical invalid assignments
```
if (Math.PI + 1 = 3 || Math.PI + 1 = 4) {
console.log('no way!');
}
// ReferenceError: invalid assignment left-hand side
const str = 'Hello, '
+= 'is it me '
+= 'you\'re looking for?';
// ReferenceError: invalid assignment left-hand side
```
In the `if` statement, you want to use an equality operator (`===`), and for the string concatenation, the plus (`+`) operator is needed.
```
if (Math.PI + 1 === 3 || Math.PI + 1 === 4) {
console.log('no way!');
}
const str = 'Hello, '
+ 'from the '
+ 'other side!';
```
See also
--------
* [Assignment operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators)
* [Equality operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators)
javascript ReferenceError: can't access lexical declaration 'X' before initialization ReferenceError: can't access lexical declaration 'X' before initialization
==========================================================================
The JavaScript exception "can't access lexical declaration `*variable*' before initialization" occurs when a lexical variable was accessed before it was initialized. This happens within any block statement, when [`let`](../statements/let) or [`const`](../statements/const) variables are accessed before the line in which they are declared is executed.
Message
-------
```
ReferenceError: Cannot access 'X' before initialization (V8-based)
ReferenceError: can't access lexical declaration 'X' before initialization (Firefox)
ReferenceError: Cannot access uninitialized variable. (Safari)
```
Error type
----------
[`ReferenceError`](../global_objects/referenceerror)What went wrong?
----------------
A lexical variable was accessed before it was initialized. This happens within any block statement, when variables declared with [`let`](../statements/let) or [`const`](../statements/const) are accessed before the line in which they are declared has been executed.
Note that it is the execution order of access and variable declaration that matters, not the order in which the lines appear in the code. For more information, see the description of [Temporal Dead Zone](../statements/let#temporal_dead_zone_tdz).
Note also that this issue does not occur for variables declared using `var`, because they are initialized with a default value of `undefined` when they are [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting).
Examples
--------
### Invalid cases
In this case, the variable `foo` is accessed before it is declared. At this point foo has not been initialized with a value, so accessing the variable throws a reference error.
```
function test() {
// Accessing the 'const' variable foo before it's declared
console.log(foo); // ReferenceError: foo is not initialized
const foo = 33; // 'foo' is declared and initialized here using the 'const' keyword
}
test();
```
### Valid cases
In the following example, we correctly declare a variable using the `const` keyword before accessing it.
```
function test() {
// Declaring variable foo
const foo = 33;
console.log(foo); // 33
}
test();
```
javascript Warning: unreachable code after return statement Warning: unreachable code after return statement
================================================
The JavaScript warning "unreachable code after return statement" occurs when using an expression after a [`return`](../statements/return) statement, or when using a semicolon-less return statement but including an expression directly after.
Message
-------
```
Warning: unreachable code after return statement (Firefox)
```
Error type
----------
Warning
What went wrong?
----------------
Unreachable code after a return statement might occur in these situations:
* When using an expression after a [`return`](../statements/return) statement, or
* when using a semicolon-less return statement but including an expression directly after.
When an expression exists after a valid `return` statement, a warning is given to indicate that the code after the `return` statement is unreachable, meaning it can never be run.
Why should I have semicolons after `return` statements? In the case of semicolon-less `return` statements, it can be unclear whether the developer intended to return the statement on the following line, or to stop execution and return. The warning indicates that there is ambiguity in the way the `return` statement is written.
Warnings will not be shown for semicolon-less returns if these statements follow it:
* [`throw`](../statements/throw)
* [`break`](../statements/break)
* [`var`](../statements/var)
* [`function`](../statements/function)
Examples
--------
### Invalid cases
```
function f() {
let x = 3;
x += 4;
return x; // return exits the function immediately
x -= 3; // so this line will never run; it is unreachable
}
function g() {
return // this is treated like `return;`
3 + 4; // so the function returns, and this line is never reached
}
```
### Valid cases
```
function f() {
let x = 3;
x += 4;
x -= 3;
return x; // OK: return after all other statements
}
function g() {
return 3 + 4 // OK: semicolon-less return with expression on the same line
}
```
See also
--------
* [Automatic Semicolon Insertion](../statements/return#automatic_semicolon_insertion)
javascript Warning: String.x is deprecated; use String.prototype.x instead Warning: String.x is deprecated; use String.prototype.x instead
===============================================================
The JavaScript warning about string generics occurs in Firefox versions prior to 68. String generics have been removed starting with Firefox 68, and these warning messages are obsolete.
Message
-------
```
Warning: String.charAt is deprecated; use String.prototype.charAt instead
Warning: String.charCodeAt is deprecated; use String.prototype.charCodeAt instead
Warning: String.concat is deprecated; use String.prototype.concat instead
Warning: String.contains is deprecated; use String.prototype.contains instead
Warning: String.endsWith is deprecated; use String.prototype.endsWith instead
Warning: String.includes is deprecated; use String.prototype.includes instead
Warning: String.indexOf is deprecated; use String.prototype.indexOf instead
Warning: String.lastIndexOf is deprecated; use String.prototype.lastIndexOf instead
Warning: String.localeCompare is deprecated; use String.prototype.localeCompare instead
Warning: String.match is deprecated; use String.prototype.match instead
Warning: String.normalize is deprecated; use String.prototype.normalize instead
Warning: String.replace is deprecated; use String.prototype.replace instead
Warning: String.search is deprecated; use String.prototype.search instead
Warning: String.slice is deprecated; use String.prototype.slice instead
Warning: String.split is deprecated; use String.prototype.split instead
Warning: String.startsWith is deprecated; use String.prototype.startsWith instead
Warning: String.substr is deprecated; use String.prototype.substr instead
Warning: String.substring is deprecated; use String.prototype.substring instead
Warning: String.toLocaleLowerCase is deprecated; use String.prototype.toLocaleLowerCase instead
Warning: String.toLocaleUpperCase is deprecated; use String.prototype.toLocaleUpperCase instead
Warning: String.toLowerCase is deprecated; use String.prototype.toLowerCase instead
Warning: String.toUpperCase is deprecated; use String.prototype.toUpperCase instead
Warning: String.trim is deprecated; use String.prototype.trim instead
Warning: String.trimLeft is deprecated; use String.prototype.trimLeft instead
Warning: String.trimRight is deprecated; use String.prototype.trimRight instead
```
Error type
----------
Warning. JavaScript execution won't be halted.
What went wrong?
----------------
The non-standard generic [`String`](../global_objects/string) methods are deprecated and have been removed in Firefox 68 and later. String generics provide `String` instance methods on the `String` object allowing `String` methods to be applied to any object.
Examples
--------
### Deprecated syntax
```
const num = 15;
String.replace(num, /5/, '2');
```
### Standard syntax
```
const num = 15;
String(num).replace(/5/, '2');
```
See also
--------
* [`String`](../global_objects/string)
| programming_docs |
javascript SyntaxError: applying the 'delete' operator to an unqualified name is deprecated SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
================================================================================
The JavaScript [strict mode](../strict_mode)-only exception "applying the 'delete' operator to an unqualified name is deprecated" occurs when variables are attempted to be deleted using the [`delete`](../operators/delete) operator.
Message
-------
```
SyntaxError: Delete of an unqualified identifier in strict mode. (V8-based)
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox)
SyntaxError: Cannot delete unqualified property 'a' in strict mode. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror) in [strict mode](../strict_mode) only.
What went wrong?
----------------
Normal variables in JavaScript can't be deleted using the [`delete`](../operators/delete) operator. In strict mode, an attempt to delete a variable will throw an error and is not allowed.
The `delete` operator can only delete properties on an object. Object properties are "qualified" if they are configurable.
Unlike what common belief suggests, the `delete` operator has **nothing** to do with directly freeing memory. Memory management is done indirectly via breaking references, see the [memory management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management) page and the [`delete`](../operators/delete) operator page for more details.
This error only happens in [strict mode code](../strict_mode). In non-strict code, the operation just returns `false`.
Examples
--------
### Freeing the contents of a variable
Attempting to delete a plain variable, doesn't work in JavaScript and it throws an error in strict mode:
```
'use strict';
var x;
// β¦
delete x;
// SyntaxError: applying the 'delete' operator to an unqualified name
// is deprecated
```
To free the contents of a variable, you can set it to [`null`](../operators/null):
```
'use strict';
var x;
// β¦
x = null;
// x can be garbage collected
```
See also
--------
* [`delete`](../operators/delete)
* [Memory management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management)
* [TypeError: property "x" is non-configurable and can't be deleted](cant_delete)
javascript TypeError: setting getter-only property "x" TypeError: setting getter-only property "x"
===========================================
The JavaScript [strict mode](../strict_mode)-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a [getter](../functions/get) is specified.
Message
-------
```
TypeError: Cannot set property x of #<Object> which has only a getter (V8-based)
TypeError: setting getter-only property "x" (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror) in [strict mode](../strict_mode) only.
What went wrong?
----------------
There is an attempt to set a new value to a property for which only a [getter](../functions/get) is specified. While this will be silently ignored in non-strict mode, it will throw a [`TypeError`](../global_objects/typeerror) in [strict mode](../strict_mode).
Examples
--------
### Property with no setter
The example below shows how to set a getter for a property. It doesn't specify a [setter](../functions/set), so a `TypeError` will be thrown upon trying to set the `temperature` property to `30`. For more details see also the [`Object.defineProperty()`](../global_objects/object/defineproperty) page.
```
"use strict";
function Archiver() {
const temperature = null;
Object.defineProperty(this, 'temperature', {
get() {
console.log('get!');
return temperature;
}
});
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 30;
// TypeError: setting getter-only property "temperature"
```
To fix this error, you will either need to remove line 16, where there is an attempt to set the temperature property, or you will need to implement a [setter](../functions/set) for it, for example like this:
```
"use strict";
function Archiver() {
let temperature = null;
const archive = [];
Object.defineProperty(this, 'temperature', {
get() {
console.log('get!');
return temperature;
},
set(value) {
temperature = value;
archive.push({ val: temperature });
}
});
this.getArchive = function() { return archive; };
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
```
See also
--------
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
* [`Object.defineProperties()`](../global_objects/object/defineproperties)
javascript SyntaxError: for-in loop head declarations may not have initializers SyntaxError: for-in loop head declarations may not have initializers
====================================================================
The JavaScript [strict mode](../strict_mode)-only exception "for-in loop head declarations may not have initializers" occurs when the head of a [for...in](../statements/for...in) contains an initializer expression, such as `for (var i = 0 in obj)`. This is not allowed in for-in loops in strict mode. In addition, lexical declarations with initializers like `for (const i = 0 in obj)` are not allowed outside strict mode either.
Message
-------
```
SyntaxError: for-in loop variable declaration may not have an initializer. (V8-based)
SyntaxError: for-in loop head declarations may not have initializers (Firefox)
SyntaxError: a lexical declaration in the head of a for-in loop can't have an initializer (Firefox)
SyntaxError: Cannot assign to the loop variable inside a for-in loop header. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
The head of a [for...in](../statements/for...in) loop contains an initializer expression. That is, a variable is declared and assigned a value `for (var i = 0 in obj)`. In non-strict mode, this head declaration is silently ignored and behaves like `for (var i in obj)`. In [strict mode](../strict_mode), however, a `SyntaxError` is thrown. In addition, lexical declarations with initializers like `for (const i = 0 in obj)` are not allowed outside strict mode either, and will always produce a `SyntaxError`.
Examples
--------
This example throws a `SyntaxError`:
```
const obj = { a: 1, b: 2, c: 3 };
for (const i = 0 in obj) {
console.log(obj[i]);
}
// SyntaxError: for-in loop head declarations may not have initializers
```
### Valid for-in loop
You can remove the initializer (`i = 0`) in the head of the for-in loop.
```
const obj = { a: 1, b: 2, c: 3 };
for (const i in obj) {
console.log(obj[i]);
}
```
### Array iteration
The for...in loop [shouldn't be used for Array iteration](../statements/for...in#array_iteration_and_for...in). Did you intend to use a [`for`](../statements/for) loop instead of a `for-in` loop to iterate an [`Array`](../global_objects/array)? The `for` loop allows you to set an initializer then as well:
```
const arr = ["a", "b", "c"];
for (let i = 2; i < arr.length; i++) {
console.log(arr[i]);
}
// "c"
```
See also
--------
* [`for...in`](../statements/for...in)
* [`for...of`](../statements/for...of) β also disallows an initializer in both strict and non-strict mode.
* [`for`](../statements/for) β preferred for array iteration, allows to define an initializer.
javascript TypeError: can't define property "x": "obj" is not extensible TypeError: can't define property "x": "obj" is not extensible
=============================================================
The JavaScript exception "can't define property "x": "obj" is not extensible" occurs when [`Object.preventExtensions()`](../global_objects/object/preventextensions) marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.
Message
-------
```
TypeError: Cannot add property x, object is not extensible (V8-based)
TypeError: Cannot define property x, object is not extensible (V8-based)
TypeError: can't define property "x": Object is not extensible (Firefox)
TypeError: Attempting to define property on object that is not extensible. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
Usually, an object is extensible and new properties can be added to it. However, in this case [`Object.preventExtensions()`](../global_objects/object/preventextensions) marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.
Examples
--------
### Adding new properties to a non-extensible objects
In [strict mode](../strict_mode), attempting to add new properties to a non-extensible object throws a `TypeError`. In sloppy mode, the addition of the "x" property is silently ignored.
```
'use strict';
const obj = {};
Object.preventExtensions(obj);
obj.x = 'foo';
// TypeError: can't define property "x": Object is not extensible
```
In both, [strict mode](../strict_mode) and sloppy mode, a call to [`Object.defineProperty()`](../global_objects/object/defineproperty) throws when adding a new property to a non-extensible object.
```
const obj = { };
Object.preventExtensions(obj);
Object.defineProperty(obj, 'x', { value: "foo" });
// TypeError: can't define property "x": Object is not extensible
```
To fix this error, you will either need to remove the call to [`Object.preventExtensions()`](../global_objects/object/preventextensions) entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. Of course you can also remove the property that was attempted to be added, if you don't need it.
```
'use strict';
const obj = {};
obj.x = 'foo'; // add property first and only then prevent extensions
Object.preventExtensions(obj);
```
See also
--------
* [`Object.preventExtensions()`](../global_objects/object/preventextensions)
javascript SyntaxError: missing } after function body SyntaxError: missing } after function body
==========================================
The JavaScript exception "missing } after function body" occurs when there is a syntax mistake when creating a function somewhere. Check if any closing curly brackets or parenthesis are in the correct order.
Message
-------
```
SyntaxError: missing } after function body (Firefox)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
There is a syntax mistake when creating a function somewhere. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle.
Examples
--------
### Forgotten closing curly bracket
Oftentimes, there is a missing curly bracket in your function code:
```
const charge = function () {
if (sunny) {
useSolarCells();
} else {
promptBikeRide();
};
```
Correct would be:
```
const charge = function () {
if (sunny) {
useSolarCells();
} else {
promptBikeRide();
}
};
```
It can be more obscure when using [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE), [Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), or other constructs that use a lot of different parenthesis and curly brackets, for example.
```
(function () { if (true) { return false; } );
```
Oftentimes, indenting differently or double checking indentation helps to spot these errors.
```
(function () {
if (true) {
return false;
}
});
```
See also
--------
* [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
javascript TypeError: "x" is (not) "y" TypeError: "x" is (not) "y"
===========================
The JavaScript exception "*x* is (not) *y*" occurs when there was an unexpected type. Oftentimes, unexpected [`undefined`](../global_objects/undefined) or [`null`](../operators/null) values.
Message
-------
```
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)
TypeError: "x" is undefined (Firefox)
TypeError: "undefined" is not an object (Firefox)
TypeError: undefined is not an object (evaluating 'obj.x') (Safari)
TypeError: "x" is not a symbol (V8-based & Firefox)
TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror).
What went wrong?
----------------
There was an unexpected type. This occurs oftentimes with [`undefined`](../global_objects/undefined) or [`null`](../operators/null) values.
Also, certain methods, such as [`Object.create()`](../global_objects/object/create) or [`Symbol.keyFor()`](../global_objects/symbol/keyfor), require a specific type, that must be provided.
Examples
--------
### Invalid cases
```
// undefined and null cases on which the substring method won't work
const foo = undefined;
foo.substring(1); // TypeError: foo is undefined
const foo = null;
foo.substring(1); // TypeError: foo is null
// Certain methods might require a specific type
const foo = {}
Symbol.keyFor(foo); // TypeError: foo is not a symbol
const foo = 'bar'
Object.create(foo); // TypeError: "foo" is not an object or null
```
### Fixing the issue
To fix null pointer to `undefined` or `null` values, you can test if the value is `undefined` or `null` first.
```
if (foo !== undefined && foo !== null) {
// Now we know that foo is defined, we are good to go.
}
```
Or, if you are confident that `foo` will not be another [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value like `""` or `0`, or if filtering those cases out is not an issue, you can simply test for its truthiness.
```
if (foo) {
// Now we know that foo is truthy, it will necessarily not be null/undefined.
}
```
See also
--------
* [`undefined`](../global_objects/undefined)
* [`null`](../operators/null)
javascript SyntaxError: redeclaration of formal parameter "x" SyntaxError: redeclaration of formal parameter "x"
==================================================
The JavaScript exception "redeclaration of formal parameter" occurs when the same variable name occurs as a function parameter and is then redeclared using a [`let`](../statements/let) assignment in a function body again.
Message
-------
```
SyntaxError: Identifier "x" has already been declared (V8-based)
SyntaxError: redeclaration of formal parameter "x" (Firefox)
SyntaxError: Cannot declare a let variable twice: 'x'. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
The same variable name occurs as a function parameter and is then redeclared using a [`let`](../statements/let) assignment in a function body again. Redeclaring the same variable within the same function or block scope using `let` is not allowed in JavaScript.
Examples
--------
### Redeclared argument
In this case, the variable "arg" redeclares the argument.
```
function f(arg) {
let arg = 'foo';
}
// SyntaxError: redeclaration of formal parameter "arg"
```
If you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. In other words: you can omit the `let` keyword. If you want to create a new variable, you need to rename it as conflicts with the function parameter already.
```
function f(arg) {
arg = 'foo';
}
function g(arg) {
let bar = 'foo';
}
```
See also
--------
* [`let`](../statements/let)
* [`const`](../statements/const)
* [`var`](../statements/var)
* [Declaring variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declarations) in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
javascript SyntaxError: missing formal parameter SyntaxError: missing formal parameter
=====================================
The JavaScript exception "missing formal parameter" occurs when your function declaration is missing valid parameters.
Message
-------
```
SyntaxError: missing formal parameter (Firefox)
SyntaxError: Unexpected number '3'. Expected a parameter pattern or a ')' in parameter list. (Safari)
SyntaxError: Unexpected string literal "x". Expected a parameter pattern or a ')' in parameter list. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
"Formal parameter" is a fancy way of saying "function parameter". Your function declaration is missing valid parameters. In the declaration of a function, the parameters must be [identifiers](https://developer.mozilla.org/en-US/docs/Glossary/Identifier), not any value like numbers, strings, or objects. Declaring functions and calling functions are two separate steps. Declarations require identifier as parameters, and only when calling (invoking) the function, you provide the values the function should use.
In [JavaScript](https://developer.mozilla.org/en-US/docs/Glossary/JavaScript), identifiers can contain only alphanumeric characters (or "$" or "\_"), and may not start with a digit. An identifier differs from a **string** in that a string is data, while an identifier is part of the code.
Examples
--------
### Provide proper function parameters
Function parameters must be identifiers when setting up a function. All these function declarations fail, as they are providing values for their parameters:
```
function square(3) {
return number \* number;
};
// SyntaxError: missing formal parameter
function greet("Howdy") {
return greeting;
};
// SyntaxError: missing formal parameter
function log({ obj: "value"}) {
console.log(arg)
};
// SyntaxError: missing formal parameter
```
You will need to use identifiers in function declarations:
```
function square(number) {
return number \* number;
};
function greet(greeting) {
return greeting;
};
function log(arg) {
console.log(arg)
};
```
You can then call these functions with the arguments you like:
```
square(2); // 4
greet("Howdy"); // "Howdy"
log({obj: "value"}); // { obj: "value" }
```
See also
--------
* Other errors regarding formal parameters:
+ [SyntaxError: Malformed formal parameter](malformed_formal_parameter)
+ [SyntaxError: redeclaration of formal parameter "x"](redeclared_parameter)
javascript RangeError: invalid date RangeError: invalid date
========================
The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to [`Date`](../global_objects/date) or [`Date.parse()`](../global_objects/date/parse).
Message
-------
```
RangeError: Invalid time value (V8-based)
RangeError: invalid date (Firefox)
RangeError: Invalid Date (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror)What went wrong?
----------------
A string leading to an invalid date has been provided to [`Date`](../global_objects/date) or [`Date.parse()`](../global_objects/date/parse).
Examples
--------
### Invalid cases
Unrecognizable strings or dates containing illegal element values in ISO formatted strings usually return [`NaN`](../global_objects/nan). However, depending on the implementation, nonβconforming ISO format strings, may also throw `RangeError: invalid date`, like the following cases in Firefox:
```
new Date('foo-bar 2014');
new Date('2014-25-23').toISOString();
new Date('foo-bar 2014').toString();
```
This, however, returns [`NaN`](../global_objects/nan) in Firefox:
```
Date.parse('foo-bar 2014'); // NaN
```
For more details, see the [`Date.parse()`](../global_objects/date/parse) documentation.
### Valid cases
```
new Date('05 October 2011 14:48 UTC');
new Date(1317826080); // Unix Timestamp for 05 October 2011 14:48:00 UTC
```
See also
--------
* [`Date`](../global_objects/date)
* [`Date.prototype.parse()`](../global_objects/date/parse)
* [`Date.prototype.toISOString()`](../global_objects/date/toisostring)
| programming_docs |
javascript SyntaxError: missing ; before statement SyntaxError: missing ; before statement
=======================================
The JavaScript exception "missing ; before statement" occurs when there is a semicolon (`;`) missing somewhere and can't be added by [automatic semicolon insertion (ASI)](../lexical_grammar#automatic_semicolon_insertion). You need to provide a semicolon, so that JavaScript can parse the source code correctly.
Message
-------
```
SyntaxError: Expected ';' (Edge)
SyntaxError: missing ; before statement (Firefox)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
There is a semicolon (`;`) missing somewhere. [JavaScript statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements) must be terminated with semicolons. Some of them are affected by [automatic semicolon insertion (ASI)](../lexical_grammar#automatic_semicolon_insertion), but in this case you need to provide a semicolon, so that JavaScript can parse the source code correctly.
However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using `var` wrongly. You might also have too many parenthesis somewhere. Carefully check the syntax when this error is thrown.
Examples
--------
### Unescaped strings
This error can occur easily when not escaping strings properly and the JavaScript engine is expecting the end of your string already. For example:
```
const foo = 'Tom's bar';
// SyntaxError: missing ; before statement
```
You can use double quotes, or escape the apostrophe:
```
const foo = "Tom's bar";
// OR
const foo = 'Tom\'s bar';
```
### Declaring properties with var
You **cannot** declare properties of an object or array with a `var` declaration.
```
const obj = {};
const obj.foo = 'hi'; // SyntaxError missing ; before statement
const array = [];
const array[0] = 'there'; // SyntaxError missing ; before statement
```
Instead, omit the `var` keyword:
```
const obj = {};
obj.foo = 'hi';
const array = [];
array[0] = 'there';
```
### Bad keywords
If you come from another programming language, it is also common to use keywords that don't mean the same or have no meaning at all in JavaScript:
```
def print(info) {
console.log(info);
} // SyntaxError missing ; before statement
```
Instead, use `function` instead of `def`:
```
function print(info) {
console.log(info);
}
```
See also
--------
* [Automatic semicolon insertion (ASI)](../lexical_grammar#automatic_semicolon_insertion)
* [JavaScript statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements)
javascript SyntaxError: Unexpected '#' used outside of class body SyntaxError: Unexpected '#' used outside of class body
======================================================
The JavaScript exception "Unexpected '#' used outside of class body" occurs when a hash ("#") is encountered in an unexpected context, most notably [outside of a class declaration](../classes/private_class_fields). Hashes are valid at the beginning of a file as a [hashbang comment](../lexical_grammar), or inside of a class as part of a private field. You may encounter this error if you forget the quotation marks when trying to access a DOM identifier as well.
Message
-------
```
SyntaxError: Unexpected '#' used outside of class body.
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
We encountered a `#` somewhere unexpected. This may be due to code moving around and no longer being part of a class, a hashbang comment found on a line other than the first line of a file, or accidentally forgetting the quotation marks around a DOM identifier.
Examples
--------
### Missing quotation marks
For each case, there might be something slightly wrong. For example
```
document.querySelector(#some-element)
```
This can be fixed via
```
document.querySelector("#some-element")
```
### Outside of a class
```
class ClassWithPrivateField {
#privateField
constructor() {
}
}
this.#privateField = 42
```
This can be fixed by moving the private field back into the class
```
class ClassWithPrivateField {
#privateField
constructor() {
this.#privateField = 42
}
}
```
See also
--------
* [`SyntaxError`](../global_objects/syntaxerror)
javascript TypeError: More arguments needed TypeError: More arguments needed
================================
The JavaScript exception "more arguments needed" occurs when there is an error with how a function is called. More arguments need to be provided.
Message
-------
```
TypeError: Object prototype may only be an Object or null: undefined (V8-based)
TypeError: Object.create requires at least 1 argument, but only 0 were passed (Firefox)
TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed (Firefox)
TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed (Firefox)
TypeError: Object prototype may only be an Object or null. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror).
What went wrong?
----------------
There is an error with how a function is called. More arguments need to be provided.
Examples
--------
### Required arguments not provided
The [`Object.create()`](../global_objects/object/create) method requires at least one argument and the [`Object.setPrototypeOf()`](../global_objects/object/setprototypeof) method requires at least two arguments:
```
const obj = Object.create();
// TypeError: Object.create requires at least 1 argument, but only 0 were passed
const obj2 = Object.setPrototypeOf({});
// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed
```
You can fix this by setting [`null`](../operators/null) as the prototype, for example:
```
const obj = Object.create(null);
const obj2 = Object.setPrototypeOf({}, null);
```
See also
--------
* [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
javascript InternalError: too much recursion InternalError: too much recursion
=================================
The JavaScript exception "too much recursion" or "Maximum call stack size exceeded" occurs when there are too many function calls, or a function is missing a base case.
Message
-------
```
RangeError: Maximum call stack size exceeded (Chrome)
InternalError: too much recursion (Firefox)
RangeError: Maximum call stack size exceeded. (Safari)
```
Error type
----------
[`InternalError`](../global_objects/internalerror) in Firefox; [`RangeError`](../global_objects/rangeerror) in Chrome and Safari.
What went wrong?
----------------
A function that calls itself is called a *recursive function*. Once a condition is met, the function stops calling itself. This is called a *base case*.
In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.
Examples
--------
This recursive function runs 10 times, as per the exit condition.
```
function loop(x) {
if (x >= 10) // "x >= 10" is the exit condition
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
```
Setting this condition to an extremely high value, won't work:
```
function loop(x) {
if (x >= 1000000000000)
return;
// do stuff
loop(x + 1);
}
loop(0);
// InternalError: too much recursion
```
This recursive function is missing a base case. As there is no exit condition, the function will call itself infinitely.
```
function loop(x) {
// The base case is missing
loop(x + 1); // Recursive call
}
loop(0);
// InternalError: too much recursion
```
### Class error: too much recursion
```
class Person {
constructor() {}
set name(name) {
this.name = name; // Recursive call
}
}
const tony = new Person();
tony.name = "Tonisha"; // InternalError: too much recursion
```
When a value is assigned to the property name (this.name = name;) JavaScript needs to set that property. When this happens, the setter function is triggered.
In this example when the setter is triggered, it is told to do the same thing again: *to set the same property that it is meant to handle.* This causes the function to call itself, again and again, making it infinitely recursive.
This issue also appears if the same variable is used in the getter.
```
class Person {
get name() {
return this.name; // Recursive call
}
}
```
To avoid this problem, make sure that the property being assigned to inside the setter function is different from the one that initially triggered the setter. The same goes for the getter.
```
class Person {
constructor() {}
set name(name) {
this._name = name;
}
get name() {
return this._name;
}
}
const tony = new Person();
tony.name = "Tonisha";
console.log(tony);
```
See also
--------
* [Recursion](https://developer.mozilla.org/en-US/docs/Glossary/Recursion)
* [Recursive functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#recursion)
javascript SyntaxError: JSON.parse: bad parsing SyntaxError: JSON.parse: bad parsing
====================================
The JavaScript exceptions thrown by [`JSON.parse()`](../global_objects/json/parse) occur when string failed to be parsed as JSON.
Message
-------
```
SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
[`JSON.parse()`](../global_objects/json/parse) parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.
Examples
--------
### JSON.parse() does not allow trailing commas
Both lines will throw a SyntaxError:
```
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}');
```
### Property names must be double-quoted strings
You cannot use single-quotes around properties, like 'foo'.
```
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data
```
Instead write "foo":
```
JSON.parse('{"foo": 1}');
```
### Leading zeros and decimal points
You cannot use leading zeros, like 01, and decimal points must be followed by at least one digit.
```
JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data
JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data
```
Instead write just 1 without a zero and use at least one digit after a decimal point:
```
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');
```
See also
--------
* [`JSON`](../global_objects/json)
* [`JSON.parse()`](../global_objects/json/parse)
* [`JSON.stringify()`](../global_objects/json/stringify)
javascript TypeError: can't assign to property "x" on "y": not an object TypeError: can't assign to property "x" on "y": not an object
=============================================================
The JavaScript strict mode exception "can't assign to property" occurs when attempting to create a property on [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) value such as a [symbol](../global_objects/symbol), a [string](https://developer.mozilla.org/en-US/docs/Glossary/String), a [number](https://developer.mozilla.org/en-US/docs/Glossary/Number) or a [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean). [Primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) values cannot hold any [property](https://developer.mozilla.org/en-US/docs/Glossary/Property/JavaScript).
Message
-------
```
TypeError: Cannot create property 'x' on number '1' (V8-based)
TypeError: can't assign to property "x" on 1: not an object (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror).
What went wrong?
----------------
In [strict mode](../strict_mode), a [`TypeError`](../global_objects/typeerror) is raised when attempting to create a property on [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) value such as a [symbol](../global_objects/symbol), a [string](https://developer.mozilla.org/en-US/docs/Glossary/String), a [number](https://developer.mozilla.org/en-US/docs/Glossary/Number) or a [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean). [Primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) values cannot hold any [property](https://developer.mozilla.org/en-US/docs/Glossary/Property/JavaScript).
The problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a [`String`](../global_objects/string) or a [`Number`](../global_objects/number) is expected.
Examples
--------
### Invalid cases
```
'use strict';
const foo = "my string";
// The following line does nothing if not in strict mode.
foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not an object
```
### Fixing the issue
Either fix the code to prevent the [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) from being used in such places, or fix the issue by creating the object equivalent [`Object`](../global_objects/object).
```
'use strict';
const foo = new String("my string");
foo.bar = {};
```
See also
--------
* [Strict mode](../strict_mode)
* [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)
javascript TypeError: can't access dead object TypeError: can't access dead object
===================================
The JavaScript exception "can't access dead object" occurs when Firefox disallows add-ons to keep strong references to DOM objects after their parent document has been destroyed to improve in memory usage and to prevent memory leaks.
Message
-------
```
TypeError: can't access dead object
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
To improve in memory usage and to prevent memory leaks, Firefox disallows add-ons to keep strong references to DOM objects after their parent document has been destroyed. A dead object, is holding a strong (keep alive) reference to a DOM element that persists even after it was destroyed in the DOM. To avoid these issues, references to DOM nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as [weak references](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.getWeakReference).
Examples
--------
### Checking if an object is dead
[Components.utils](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils) offers a `isDeadWrapper()` method, which privileged code might use.
```
if (Components.utils.isDeadWrapper(window)) {
// dead
}
```
Unprivileged code has no access to Component.utils and might just be able catch the exception.
```
try {
String(window);
}
catch (e) {
console.log("window is likely dead");
}
```
See also
--------
* [What does "can't access dead object" mean?](https://blog.mozilla.org/addons/2012/09/12/what-does-cant-access-dead-object-mean/)
* [Common causes of memory leaks in extensions](https://developer.mozilla.org/en-US/docs/Extensions/Common_causes_of_memory_leaks_in_extensions)
* [Components.utils](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils)
* [Zombie Compartments](https://developer.mozilla.org/en-US/docs/Mozilla/Zombie_compartments)
javascript RangeError: radix must be an integer RangeError: radix must be an integer
====================================
The JavaScript exception "radix must be an integer at least 2 and no greater than 36" occurs when the optional `radix` parameter of the [`Number.prototype.toString()`](../global_objects/number/tostring) or the [`BigInt.prototype.toString()`](../global_objects/bigint/tostring) method was specified and is not between 2 and 36.
Message
-------
```
RangeError: toString() radix argument must be between 2 and 36 (V8-based & Safari)
RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror)What went wrong?
----------------
The optional `radix` parameter of the [`Number.prototype.toString()`](../global_objects/number/tostring) or the [`BigInt.prototype.toString()`](../global_objects/bigint/tostring) method was specified. Its value must be an integer (a number) between 2 and 36, specifying the base of the number system to be used for representing numeric values. For example, the decimal (base 10) number 169 is represented in hexadecimal (base 16) as A9.
Why is this parameter's value limited to 36? A radix that is larger than 10 uses alphabetical characters as digits; therefore, the radix can't be larger than 36, since the Latin alphabet (used by English and many other languages) only has 26 characters.
The most common radixes:
* 2 for [binary numbers](https://en.wikipedia.org/wiki/Binary_number),
* 8 for [octal numbers](https://en.wikipedia.org/wiki/Octal),
* 10 for [decimal numbers](https://en.wikipedia.org/wiki/Decimal),
* 16 for [hexadecimal numbers](https://en.wikipedia.org/wiki/Hexadecimal).
Examples
--------
### Invalid cases
```
(42).toString(0);
(42).toString(1);
(42).toString(37);
(42).toString(150);
// You cannot use a string like this for formatting:
(12071989).toString('MM-dd-yyyy');
```
### Valid cases
```
(42).toString(2); // "101010" (binary)
(13).toString(8); // "15" (octal)
(0x42).toString(10); // "66" (decimal)
(100000).toString(16) // "186a0" (hexadecimal)
```
See also
--------
* [`Number.prototype.toString()`](../global_objects/number/tostring)
* [`BigInt.prototype.toString()`](../global_objects/bigint/tostring)
| programming_docs |
javascript SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
=============================================================================
The JavaScript exception "cannot use `??` unparenthesized within `||` and `&&` expressions" occurs when an [nullish coalescing operator](../operators/nullish_coalescing) is used with a [logical OR](../operators/logical_or) or [logical AND](../operators/logical_and) in the same expression without parentheses.
Message
-------
```
SyntaxError: Unexpected token '??' (V8-based)
SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions (Firefox)
SyntaxError: Unexpected token '??'. Coalescing and logical operators used together in the same expression; parentheses must be used to disambiguate. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
The [operator precedence](../operators/operator_precedence) chain looks like this:
```
| > && > || > =
| > ?? > =
```
However, the precedence *between* `??` and `&&`/`||` is intentionally undefined, because the short circuiting behavior of logical operators can make the expression's evaluation counter-intuitive. Therefore, the following combinations are all syntax errors, because the language doesn't know how to parenthesize the operands:
```
a ?? b || c
a || b ?? c
a ?? b && c
a && b ?? c
```
Instead, make your intent clear by parenthesizing either side explicitly:
```
(a ?? b) || c
a ?? (b && c)
```
Examples
--------
When migrating legacy code that uses `||` and `&&` for guarding against `null` or `undefined`, you may often convert it partially:
```
function getId(user, fallback) {
// Previously: user && user.id || fallback
return user && user.id ?? fallback; // SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
}
```
Instead, consider parenthesizing the `&&`:
```
function getId(user, fallback) {
return (user && user.id) ?? fallback;
}
```
Even better, consider using [optional chaining](../operators/optional_chaining) instead of `&&`:
```
function getId(user, fallback) {
return user?.id ?? fallback;
}
```
See also
--------
* [Original discussion of nullish coalescing precedence](https://github.com/tc39/proposal-nullish-coalescing/issues/15)
* [Nullish coalescing operator](../operators/nullish_coalescing)
* [Operator precedence](../operators/operator_precedence)
javascript SyntaxError: return not in function SyntaxError: return not in function
===================================
The JavaScript exception "return (or yield) not in function" occurs when a [`return`](../statements/return) or [`yield`](../operators/yield) statement is called outside of a [function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions).
Message
-------
```
SyntaxError: Illegal return statement (V8-based)
SyntaxError: return not in function (Firefox)
SyntaxError: Return statements are only valid inside functions. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
A [`return`](../statements/return) or [`yield`](../operators/yield) statement is called outside of a [function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions). Maybe there are missing curly brackets somewhere? The `return` and `yield` statements must be in a function, because they end (or pause and resume) function execution and specify a value to be returned to the function caller.
Examples
--------
### Missing curly brackets
```
function cheer(score) {
if (score === 147)
return 'Maximum!';
}
if (score > 100) {
return 'Century!';
}
}
// SyntaxError: return not in function
```
The curly brackets look correct at a first glance, but this code snippet is missing a `{` after the first `if` statement. Correct would be:
```
function cheer(score) {
if (score === 147) {
return 'Maximum!';
}
if (score > 100) {
return 'Century!';
}
}
```
See also
--------
* [`return`](../statements/return)
* [`yield`](../operators/yield)
javascript SyntaxError: missing : after property id SyntaxError: missing : after property id
========================================
The JavaScript exception "missing : after property id" occurs when objects are created using the [object initializer](../operators/object_initializer) syntax. A colon (`:`) separates keys and values for the object's properties. Somehow, this colon is missing or misplaced.
Message
-------
```
SyntaxError: Invalid shorthand property initializer (V8-based)
SyntaxError: missing : after property id (Firefox)
SyntaxError: Unexpected token '='. Expected a ':' following the property name 'x'. (Safari)
SyntaxError: Unexpected token '+'. Expected an identifier as property name. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
When creating objects with the [object initializer](../operators/object_initializer) syntax, a colon (`:`) separates keys and values for the object's properties.
```
const obj = { propertyKey: 'value' };
```
Examples
--------
### Colons vs. equal signs
This code fails, as the equal sign can't be used this way in this object initializer syntax.
```
const obj = { propertyKey = 'value' };
// SyntaxError: missing : after property id
```
Correct would be to use a colon, or to use square brackets to assign a new property after the object has been created already.
```
const obj = { propertyKey: 'value' };
// or alternatively
const obj = {};
obj['propertyKey'] = 'value';
```
### Computed properties
If you create a property key from an expression, you need to use square brackets. Otherwise the property name can't be computed:
```
const obj = { 'b'+'ar': 'foo' };
// SyntaxError: missing : after property id
```
Put the expression in brackets `[]`:
```
const obj = { ['b'+'ar']: 'foo' };
```
See also
--------
* [Object initializer](../operators/object_initializer)
javascript Warning: 08/09 is not a legal ECMA-262 octal constant Warning: 08/09 is not a legal ECMA-262 octal constant
=====================================================
The JavaScript warning "08 (or 09) is not a legal ECMA-262 octal constant" occurs when `08` or `09` number literals are used. They can't be interpreted as an octal number.
Message
-------
```
Warning: SyntaxError: 08 is not a legal ECMA-262 octal constant.
```
Error type
----------
Warning. JavaScript execution won't be halted.
What went wrong?
----------------
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. Because this is not the case with `08` and `09`, JavaScript warns about it.
Note that octal literals and octal escape sequences are deprecated and will present an additional deprecation warning. The standardized syntax for octal literals uses a leading zero followed by a lowercase or uppercase Latin letter "O" (`0o` or `0O)`. See the page about [lexical grammar](../lexical_grammar#octal) for more information.
Examples
--------
### Invalid octal numbers
```
08;
09;
// SyntaxError: 08 is not a legal ECMA-262 octal constant
// SyntaxError: "0"-prefixed octal literals and octal escape sequences
// are deprecated
```
### Valid octal numbers
Use a leading zero followed by the letter "o";
```
0O755;
0o644;
```
See also
--------
* [Lexical grammar](../lexical_grammar#octal)
* [SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated](deprecated_octal)
javascript SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**' SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '\*\*'
==========================================================================================
The JavaScript exception "unparenthesized unary expression can't appear on the left-hand side of '\*\*'" occurs when a unary operator (one of `typeof`, `void`, `delete`, `await`, `!`, `~`, `+`, `-`) is used on the left operand of the [exponentiation operator](../operators/exponentiation) without parentheses.
Message
-------
```
SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence (V8-based)
SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**' (Firefox)
SyntaxError: Unexpected token '**'. Ambiguous unary expression in the left hand side of the exponentiation expression; parentheses must be used to disambiguate the expression. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
You likely wrote something like this:
```
-a \*\* b
```
Whether it should be evaluated as `(-a) ** b` or `-(a ** b)` is ambiguous. In mathematics, -x2 means `-(x ** 2)` β and that's how many languages, including Python, Haskell, and PHP, handle it. But making the unary minus operator take precedence over `**` breaks symmetry with `a ** -b`, which is unambiguously `a ** (-b)`. Therefore, the language forbids this syntax and requires you to parenthesize either side to resolve the ambiguity.
```
(-a) \*\* b
-(a \*\* b)
```
Other unary operators cannot be the left-hand side of exponentiation either.
```
await a \*\* b
!a \*\* b
+a \*\* b
~a \*\* b
```
Examples
--------
When writing complex math expressions involving exponentiation, you may write something like this:
```
function taylorSin(x) {
return (n) => -1 \*\* n \* x \*\* (2 \* n + 1) / factorial(2 \* n + 1);
// SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '\*\*'
}
```
However, the `-1 ** n` part is illegal in JavaScript. Instead, parenthesize the left operand:
```
function taylorSin(x) {
return (n) => (-1) \*\* n \* x \*\* (2 \* n + 1) / factorial(2 \* n + 1);
}
```
This also makes the code's intent much clearer to other readers.
See also
--------
* [Original discussion of exponentiation operator precedence](https://esdiscuss.org/topic/exponentiation-operator-precedence)
* [Exponentiation operator](../operators/exponentiation)
* [Operator precedence](../operators/operator_precedence)
javascript ReferenceError: deprecated caller or arguments usage ReferenceError: deprecated caller or arguments usage
====================================================
The JavaScript [strict mode](../strict_mode)-only exception "deprecated caller or arguments usage" occurs when the deprecated [`Function.prototype.caller`](../global_objects/function/caller) or [`Function.prototype.arguments`](../global_objects/function/arguments) properties are used.
Message
-------
```
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them (V8-based & Firefox)
TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror) in [strict mode](../strict_mode) only.
What went wrong?
----------------
In [strict mode](../strict_mode), the [`Function.prototype.caller`](../global_objects/function/caller) or [`Function.prototype.arguments`](../global_objects/function/arguments) properties are used and shouldn't be. They are deprecated, because they leak the function caller, are non-standard, hard to optimize and potentially a performance-harmful feature.
Examples
--------
### Deprecated function.caller or arguments.callee.caller
[`Function.prototype.caller`](../global_objects/function/caller) and [`arguments.callee.caller`](../functions/arguments/callee) are deprecated (see the reference articles for more information).
```
'use strict';
function myFunc() {
if (myFunc.caller === null) {
return 'The function was called from the top!';
} else {
return `This function's caller was ${myFunc.caller}`;
}
}
myFunc();
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
```
### Function.prototype.arguments
[`Function.prototype.arguments`](../global_objects/function/arguments) is deprecated (see the reference article for more information).
```
'use strict';
function f(n) { g(n - 1); }
function g(n) {
console.log(`before: ${g.arguments[0]}`);
if (n > 0) { f(n); }
console.log(`after: ${g.arguments[0]}`);
}
f(2);
console.log(`returned: ${g.arguments}`);
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
```
See also
--------
* [Deprecated and obsolete features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features)
* [Strict mode](../strict_mode)
* [`Function.prototype.arguments`](../global_objects/function/arguments)
* [`Function.prototype.caller`](../global_objects/function/caller) and [`arguments.callee.caller`](../functions/arguments/callee)
javascript SyntaxError: invalid regular expression flag "x" SyntaxError: invalid regular expression flag "x"
================================================
The JavaScript exception "invalid regular expression flag" occurs when the flags in a regular expression contain any flag that is not one of: `g`, `i`, `m`, `s`, `u`, `y` or `d`.
It may also be raised if the expression contains more than one instance of a valid flag.
Message
-------
```
SyntaxError: Invalid regular expression flags (V8-based)
SyntaxError: invalid regular expression flag x (Firefox)
SyntaxError: Invalid regular expression: invalid flags (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
The regular expression contains invalid flags, or valid flags have been used more than once in the expression.
The valid (allowed) flags are listed in [Regular expressions > Advanced searching with flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags), and reproduced below:
| Flag | Description |
| --- | --- |
| `g` | Global search. See [`global`](../global_objects/regexp/global) |
| `i` | Case-insensitive search. See [`ignoreCase`](../global_objects/regexp/sticky). |
| `m` | Multi-line search. See [`multiline`](../global_objects/regexp/multiline). |
| `s` | Allow `.` to match newlines. See [`dotAll`](../global_objects/regexp/dotall). |
| `u` | Unicode; treat pattern as a sequence of Unicode code points. See [`unicode`](../global_objects/regexp/unicode). |
| `y` | Perform a "sticky" search that matches starting at the current position in the target string. See [`sticky`](../global_objects/regexp/sticky) |
| `d` | Indices. Generate indices for substring matches. See [`hasIndices`](../global_objects/regexp/hasindices) |
Examples
--------
In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. Regular expression flags can be used separately or together in any order. This syntax shows how to declare the flags using the regular expression literal:
```
const re = /pattern/flags;
```
They can also be defined in the constructor function of the [`RegExp`](../global_objects/regexp) object (second parameter):
```
const re = new RegExp('pattern', 'flags');
```
Here is an example showing use of only correct flags.
```
/foo/g;
/foo/gims;
/foo/uy;
```
Below is an example showing the use of some invalid flags `b`, `a` and `r`:
```
/foo/bar;
// SyntaxError: invalid regular expression flag "b"
```
The code below is incorrect, because `W`, `e` and `b` are not valid flags.
```
const obj = {
url: /docs/Web,
};
// SyntaxError: invalid regular expression flag "W"
```
An expression containing two slashes is interpreted as a regular expression literal. Most likely the intent was to create a string literal, using single or double quotes as shown below:
```
const obj = {
url: '/docs/Web',
};
```
See also
--------
* [Regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
* [XRegEx flags](https://xregexp.com/flags/) β regular expression library that provides four new flags (`n`, `s`, `x`, `A`)
javascript TypeError: "x" has no properties TypeError: "x" has no properties
================================
The JavaScript exception "null (or undefined) has no properties" occurs when you attempt to access properties of [`null`](../operators/null) and [`undefined`](../global_objects/undefined). They don't have any.
Message
-------
```
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)
TypeError: null has no properties (Firefox)
TypeError: undefined has no properties (Firefox)
TypeError: undefined is not an object (evaluating 'undefined.x') (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror).
What went wrong?
----------------
Both [`null`](../operators/null) and [`undefined`](../global_objects/undefined), have no properties you could access.
Examples
--------
### null and undefined have no properties
```
null.foo;
// TypeError: null has no properties
undefined.bar;
// TypeError: undefined has no properties
```
See also
--------
* [`null`](../operators/null)
* [`undefined`](../global_objects/undefined)
javascript TypeError: property "x" is non-configurable and can't be deleted TypeError: property "x" is non-configurable and can't be deleted
================================================================
The JavaScript exception "property is non-configurable and can't be deleted" occurs when it was attempted to delete a property, but that property is [non-configurable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties).
Message
-------
```
TypeError: Cannot delete property 'x' of #<Object> (V8-based)
TypeError: property "x" is non-configurable and can't be deleted (Firefox)
TypeError: Unable to delete property. (Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror) in strict mode only.
What went wrong?
----------------
It was attempted to delete a property, but that property is [non-configurable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties). The `configurable` attribute controls whether the property can be deleted from the object and whether its attributes (other than `writable`) can be changed.
This error happens only in [strict mode code](../strict_mode). In non-strict code, the operation returns `false`.
Examples
--------
### Attempting to delete non-configurable properties
Non-configurable properties are not super common, but they can be created using [`Object.defineProperty()`](../global_objects/object/defineproperty) or [`Object.freeze()`](../global_objects/object/freeze).
```
'use strict';
const obj = Object.freeze({name: 'Elsa', score: 157});
delete obj.score; // TypeError
```
```
'use strict';
const obj = {};
Object.defineProperty(obj, 'foo', {value: 2, configurable: false});
delete obj.foo; // TypeError
```
```
'use strict';
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray.pop(); // TypeError
```
There are also a few non-configurable properties built into JavaScript. Maybe you tried to delete a mathematical constant.
```
'use strict';
delete Math.PI; // TypeError
```
See also
--------
* [delete operator](../operators/delete)
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
* [`Object.freeze()`](../global_objects/object/freeze)
| programming_docs |
javascript RangeError: BigInt negative exponent RangeError: BigInt negative exponent
====================================
The JavaScript exception "BigInt negative exponent" occurs when a [`BigInt`](../global_objects/bigint) is raised to the power of a negative BigInt value.
Message
-------
```
RangeError: Exponent must be positive (V8-based)
RangeError: BigInt negative exponent (Firefox)
RangeError: Negative exponent is not allowed (Safari)
```
Error type
----------
[`RangeError`](../global_objects/rangeerror).
What went wrong?
----------------
The exponent of an [exponentiation](../operators/exponentiation) operation must be positive. Since negative exponents would take the reciprocal of the base, the result will be between -1 and 1 in almost all cases, which gets rounded to `0n`. To catch mistakes, negative exponents are not allowed. Check if the exponent is non-negative before doing exponentiation.
Examples
--------
### Using a negative BigInt as exponent
```
const a = 1n;
const b = -1n;
const c = a \*\* b;
// RangeError: BigInt negative exponent
```
Instead, check if the exponent is negative first, and either issue an error with a better message, or fallback to a different value, like `0n` or `undefined`.
```
const a = 1n;
const b = -1n;
const quotient = b >= 0n ? a \*\* b : 0n;
```
See also
--------
* [`BigInt`](../global_objects/bigint)
* [Exponentiation](../operators/exponentiation)
javascript SyntaxError: missing ) after argument list SyntaxError: missing ) after argument list
==========================================
The JavaScript exception "missing ) after argument list" occurs when there is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string.
Message
-------
```
SyntaxError: missing ) after argument list (V8-based & Firefox)
SyntaxError: Unexpected identifier 'x'. Expected ')' to end an argument list. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
There is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string, for example.
Examples
--------
Because there is no "+" operator to concatenate the string, JavaScript expects the argument for the `log` function to be just `"PI: "`. In that case, it should be terminated by a closing parenthesis.
```
console.log('PI: ' Math.PI);
// SyntaxError: missing ) after argument list
```
You can correct the `log` call by adding the `+` operator:
```
console.log('PI: ' + Math.PI);
// "PI: 3.141592653589793"
```
Alternatively, you can consider using a [template literal](../template_literals), or take advantage of the fact that [`console.log`](https://developer.mozilla.org/en-US/docs/Web/API/console/log) accepts multiple parameters:
```
console.log(`PI: ${Math.PI}`);
console.log('PI: ', Math.PI);
```
### Unterminated strings
```
console.log('"Java" + "Script" = \"' + 'Java' + 'Script\");
// SyntaxError: missing ) after argument list
```
Here JavaScript thinks that you meant to have `);` inside the string and ignores it, and it ends up not knowing that you meant the `);` to end the function `console.log`. To fix this, we could put a`'` after the "Script" string:
```
console.log('"Java" + "Script" = "' + 'Java' + 'Script"');
// '"Java" + "Script" = "JavaScript"'
```
See also
--------
* [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
javascript SyntaxError: "x" is a reserved identifier SyntaxError: "x" is a reserved identifier
=========================================
The JavaScript exception "*variable* is a reserved identifier" occurs when [reserved keywords](../lexical_grammar#keywords) are used as identifiers.
Message
-------
```
SyntaxError: Unexpected reserved word (V8-based)
SyntaxError: implements is a reserved identifier (Firefox)
SyntaxError: Cannot use the reserved word 'implements' as a variable name. (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror)What went wrong?
----------------
[Reserved keywords](../lexical_grammar#keywords) will throw in if they are used as identifiers. These are reserved in strict mode and sloppy mode:
* `enum`
The following are only reserved when they are found in strict mode code:
* `implements`
* `interface`
* [`let`](../statements/let)
* `package`
* `private`
* `protected`
* `public`
* `static`
Examples
--------
### Strict and non-strict reserved keywords
The `enum` identifier is generally reserved.
```
const enum = { RED: 0, GREEN: 1, BLUE: 2 };
// SyntaxError: enum is a reserved identifier
```
In strict mode code, more identifiers are reserved.
```
"use strict";
const package = ["potatoes", "rice", "fries"];
// SyntaxError: package is a reserved identifier
```
You'll need to rename these variables.
```
const colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
const list = ["potatoes", "rice", "fries"];
```
### Update older browsers
If you are using an older browser that does not yet implement [`let`](../statements/let) or [`class`](../statements/class), for example, you should update to a more recent browser version that does support these new language features.
```
"use strict";
class DocArchiver {}
// SyntaxError: class is a reserved identifier
// (throws in older browsers only, e.g. Firefox 44 and older)
```
See also
--------
* [Good variable names](https://wiki.c2.com/?GoodVariableNames)
javascript SyntaxError: invalid BigInt syntax SyntaxError: invalid BigInt syntax
==================================
The JavaScript exception "invalid BigInt syntax" occurs when a string value is being coerced to a [`BigInt`](../global_objects/bigint) but it failed to be parsed as an integer.
Message
-------
```
SyntaxError: Cannot convert x to a BigInt (V8-based)
SyntaxError: invalid BigInt syntax (Firefox)
SyntaxError: Failed to parse String to BigInt (Safari)
```
Error type
----------
[`SyntaxError`](../global_objects/syntaxerror).
What went wrong?
----------------
When using the [`BigInt()`](../global_objects/bigint/bigint) function to convert a string to a BigInt, the string will be parsed in the same way as source code, and the resulting value must be an integer value.
Examples
--------
### Invalid cases
```
const a = BigInt("1.5");
const b = BigInt("1n");
const c = BigInt.asIntN(4, "8n");
// SyntaxError: invalid BigInt syntax
```
### Valid cases
```
const a = BigInt("1");
const b = BigInt(" 1 ");
const c = BigInt.asIntN(4, "8");
```
See also
--------
* [`BigInt`](../global_objects/bigint)
javascript Warning: Date.prototype.toLocaleFormat is deprecated Warning: Date.prototype.toLocaleFormat is deprecated
====================================================
The JavaScript warning "Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead" occurs when the non-standard `Date.prototype.toLocaleFormat()` method is used. `toLocaleFormat()` is now removed and this warning message is obsolete.
Message
-------
```
Warning: Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead
```
Error type
----------
Warning. JavaScript execution won't be halted.
What went wrong?
----------------
The non-standard `Date.prototype.toLocaleFormat()` method is deprecated and shouldn't be used anymore. It uses a format string in the same format expected by the `strftime()` function in C. **The function is no longer available in Firefox 58+**.
Examples
--------
### Deprecated syntax
The `Date.prototype.toLocaleFormat()` method is deprecated and will be removed (no cross-browser support, available in Firefox only).
```
const today = new Date();
const date = today.toLocaleFormat("%A, %e. %B %Y");
console.log(date);
// In German locale
// "Freitag, 10. MΓ€rz 2017"
```
### Alternative standard syntax using the ECMAScript Intl API
The ECMA-402 (ECMAScript Intl API) standard specifies standard objects and methods that enable language sensitive date and time formatting (available in Chrome 24+, Firefox 29+, IE11+, Safari10+).
You can now either use the [`Date.prototype.toLocaleDateString`](../global_objects/date/tolocaledatestring) method if you just want to format one date.
```
const today = new Date();
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const date = today.toLocaleDateString("de-DE", options);
console.log(date);
// "Freitag, 10. MΓ€rz 2017"
```
Or, you can make use of the [`Intl.DateTimeFormat`](../global_objects/intl/datetimeformat) object, which allows you to cache an object with most of the computations done so that formatting is fast. This is useful if you have a loop of dates to format.
```
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const dateFormatter = new Intl.DateTimeFormat("de-DE", options);
const dates = [Date.UTC(2012, 11, 20, 3, 0, 0), Date.UTC(2014, 4, 12, 8, 0, 0)];
dates.forEach((date) => console.log(dateFormatter.format(date)));
// "Donnerstag, 20. Dezember 2012"
// "Montag, 12. Mai 2014"
```
### Alternative standard syntax using Date methods
The [`Date`](../global_objects/date) object offers several methods to build a custom date string.
```
new Date().toLocaleFormat("%Y%m%d");
// "20170310"
```
Can be converted to:
```
const now = new Date();
const date =
now.getFullYear() \* 10000 + (now.getMonth() + 1) \* 100 + now.getDate();
console.log(date);
// "20170310"
```
See also
--------
* [`Date.prototype.toLocaleDateString`](../global_objects/date/tolocaledatestring)
* [`Intl.DateTimeFormat`](../global_objects/intl/datetimeformat)
javascript TypeError: "x" is not a function TypeError: "x" is not a function
================================
The JavaScript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function.
Message
-------
```
TypeError: "x" is not a function. (V8-based & Firefox & Safari)
```
Error type
----------
[`TypeError`](../global_objects/typeerror)What went wrong?
----------------
It attempted to call a value from a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.
Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript `Objects` have no `map` function, but the JavaScript `Array` object does.
There are many built-in functions in need of a (callback) function. You will have to provide a function in order to have these methods working properly:
* When working with [`Array`](../global_objects/array) or [`TypedArray`](../global_objects/typedarray) objects:
+ [`Array.prototype.every()`](../global_objects/array/every), [`Array.prototype.some()`](../global_objects/array/some), [`Array.prototype.forEach()`](../global_objects/array/foreach), [`Array.prototype.map()`](../global_objects/array/map), [`Array.prototype.filter()`](../global_objects/array/filter), [`Array.prototype.reduce()`](../global_objects/array/reduce), [`Array.prototype.reduceRight()`](../global_objects/array/reduceright), [`Array.prototype.find()`](../global_objects/array/find)
* When working with [`Map`](../global_objects/map) and [`Set`](../global_objects/set) objects:
+ [`Map.prototype.forEach()`](../global_objects/map/foreach) and [`Set.prototype.forEach()`](../global_objects/set/foreach)
Examples
--------
### A typo in the function name
In this case, which happens way too often, there is a typo in the method name:
```
const x = document.getElementByID('foo');
// TypeError: document.getElementByID is not a function
```
The correct function name is `getElementById`:
```
const x = document.getElementById('foo');
```
### Function called on the wrong object
For certain methods, you have to provide a (callback) function and it will work on specific objects only. In this example, [`Array.prototype.map()`](../global_objects/array/map) is used, which will work with [`Array`](../global_objects/array) objects only.
```
const obj = { a: 13, b: 37, c: 42 };
obj.map(function (num) {
return num \* 2;
});
// TypeError: obj.map is not a function
```
Use an array instead:
```
const numbers = [1, 4, 9];
numbers.map(function (num) {
return num \* 2;
}); // [2, 8, 18]
```
### Function shares a name with a pre-existing property
Sometimes when making a class, you may have a property and a function with the same name. Upon calling the function, the compiler thinks that the function ceases to exist.
```
function Dog() {
this.age = 11;
this.color = "black";
this.name = "Ralph";
return this;
}
Dog.prototype.name = function (name) {
this.name = name;
return this;
}
const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
```
Use a different property name instead:
```
function Dog() {
this.age = 11;
this.color = "black";
this.dogName = "Ralph"; //Using this.dogName instead of .name
return this;
}
Dog.prototype.name = function (name) {
this.dogName = name;
return this;
}
const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
```
### Using brackets for multiplication
In math, you can write 2 Γ (3 + 5) as 2\*(3 + 5) or just 2(3 + 5).
Using the latter will throw an error:
```
const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// Uncaught TypeError: 2 is not a function
```
You can correct the code by adding a `*` operator:
```
const sixteen = 2 \* (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// 2 x (3 + 5) is 16
```
### Import the exported module correctly
Ensure you are importing the module correctly.
An example helpers library (`helpers.js`)
```
const helpers = function () { };
helpers.groupBy = function (objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
acc[key] ??= [];
acc[key].push(obj);
return acc;
}, {});
}
export default helpers;
```
The correct import usage (`App.js`):
```
import helpers from './helpers';
```
See also
--------
* [Functions](../functions)
javascript Error: Permission denied to access property "x" Error: Permission denied to access property "x"
===============================================
The JavaScript exception "Permission denied to access property" occurs when there was an attempt to access an object for which you have no permission.
Message
-------
```
DOMException: Blocked a frame with origin "x" from accessing a cross-origin frame. (Chromium-based)
DOMException: Permission denied to access property "x" on cross-origin object (Firefox)
SecurityError: Blocked a frame with origin "x" from accessing a cross-origin frame. Protocols, domains, and ports must match. (Safari)
```
Error type
----------
[`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException).
What went wrong?
----------------
There was attempt to access an object for which you have no permission. This is likely an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) element loaded from a different domain for which you violated the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
Examples
--------
### No permission to access document
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<iframe
id="myframe"
src="http://www1.w3c-test.org/common/blank.html"></iframe>
<script>
onload = function () {
console.log(frames[0].document);
// Error: Permission denied to access property "document"
};
</script>
</head>
<body></body>
</html>
```
See also
--------
* [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)
* [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)
statsmodels Installation Installation
============
Using setuptools
----------------
To obtain the latest released version of statsmodels using pip
pip install -U statsmodels Or follow [this link to our PyPI page](https://pypi.python.org/pypi/statsmodels), download the wheel or source and install.
Statsmodels is also available in through conda provided by [Anaconda](https://www.continuum.io/downloads). The latest release can be installed using
conda install -c conda-forge statsmodels Obtaining the Source
--------------------
We do not release very often but the master branch of our source code is usually fine for everyday use. You can get the latest source from our [github repository](https://github.com/statsmodels/statsmodels). Or if you have git installed:
```
git clone git://github.com/statsmodels/statsmodels.git
```
If you want to keep up to date with the source on github just periodically do:
```
git pull
```
in the statsmodels directory.
Installation from Source
------------------------
You will need a C compiler installed to build statsmodels. If you are building from the github source and not a source release, then you will also need Cython. You can follow the instructions below to get a C compiler setup for Windows.
### Linux
Once you have obtained the source, you can do (with appropriate permissions):
```
python setup.py install
```
Or:
```
python setup.py build
python setup.py install
```
### Windows
It is strongly recommended to use 64-bit Python if possible.
Python 2.7
----------
Obtain [Microsoft Visual C++ Compiler for Python 2.7](https://www.microsoft.com/en-gb/download/details.aspx?id=44266) and then install using
python setup.py install Python 3.5
----------
Download and install the most recent version of [Visual Studio Community Edition](https://www.visualstudio.com/vs/community/) and then install using
python setup.py install 32-bit or other versions of Python
----------------------------------
You can build 32-bit version of the code on windows using mingw32.
First, get and install [mingw32](http://www.mingw.org/). Then, youβll need to edit distutils.cfg. This is usually found somewhere like C:Python27Libdistutilsdistutils.cfg. Add these lines:
```
[build]
compiler=mingw32
```
Then in the statsmodels directory do:
```
python setup.py build
python setup.py install
```
OR
You can build 32-bit Microsoft SDK. Detailed instructions can be found on the Cython wiki [here](https://github.com/cython/cython/wiki/CythonExtensionsOnWindows). The gist of these instructions follow. You will need to download the free Windows SDK C/C++ compiler from Microsoft. You must use the **Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1** to be comptible with Python 2.7, 3.1, and 3.2. The link for the 3.5 SP1 version is
<https://www.microsoft.com/en-us/download/details.aspx?id=18950>
For Python 3.3 and 3.4, you need to use the **Microsoft Windows SDK for Windows 7 and .NET Framework 4**, available from
<https://www.microsoft.com/en-us/download/details.aspx?id=8279>
For 7.0, get the ISO file GRMSDKX\_EN\_DVD.iso for AMD64. After you install this, open the SDK Command Shell (Start -> All Programs -> Microsoft Windows SDK v7.0 -> CMD Shell). CD to the statsmodels directory and type:
```
set DISTUTILS_USE_SDK=1
```
To build a 64-bit application type:
```
setenv /x64 /release
```
To build a 32-bit application type:
```
setenv /x86 /release
```
The prompt should change colors to green. Then proceed as usual to install:
```
python setup.py build
python setup.py install
```
For 7.1, the instructions are exactly the same, except you use the download link provided above and make sure you are using SDK 7.1.
If you want to accomplish the same without opening up the SDK CMD SHELL, then you can use these commands at the CMD Prompt or in a batch file.:
```
setlocal EnableDelayedExpansion
CALL "C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\SetEnv.cmd" /x64 /release
set DISTUTILS_USE_SDK=1
```
Replace `/x64` with `/x86` and `v7.0` with `v7.1` as needed.
Dependencies
------------
* [Python](https://www.python.org) >= 2.7, including Python 3.x
* [NumPy](http://www.scipy.org/) >= 1.8
* [SciPy](http://www.scipy.org/) >= 0.14
* [Pandas](http://pandas.pydata.org/) >= 0.14
* [Patsy](https://patsy.readthedocs.io/en/latest/) >= 0.3.0
* [Cython](http://cython.org/) >= 0.24 is required to build the code from github but not from a source distribution.
Optional Dependencies
---------------------
* [Matplotlib](http://matplotlib.org/) >= 1.4 is needed for plotting functions and running many of the examples.
* If installed, [X-12-ARIMA](http://www.census.gov/srd/www/x13as/) or [X-13ARIMA-SEATS](http://www.census.gov/srd/www/x13as/) can be used for time-series analysis.
* [Nose](https://nose.readthedocs.org/en/latest) is required to run the test suite.
* [IPython](http://ipython.org) >= 3.0 is required to build the docs locally or to use the notebooks.
* [joblib](http://pythonhosted.org/joblib/) >= 0.9 can be used to accelerate distributed estimation for certain models.
* [jupyter](http://jupyter.org/) is needed to run the notebooks.
| programming_docs |
statsmodels Patsy: Contrast Coding Systems for categorical variables Patsy: Contrast Coding Systems for categorical variables
========================================================
Note
This document is based heavily on [this excellent resource from UCLA](http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm).
A categorical variable of K categories, or levels, usually enters a regression as a sequence of K-1 dummy variables. This amounts to a linear hypothesis on the level means. That is, each test statistic for these variables amounts to testing whether the mean for that level is statistically significantly different from the mean of the base category. This dummy coding is called Treatment coding in R parlance, and we will follow this convention. There are, however, different coding methods that amount to different sets of linear hypotheses.
In fact, the dummy coding is not technically a contrast coding. This is because the dummy variables add to one and are not functionally independent of the modelβs intercept. On the other hand, a set of *contrasts* for a categorical variable with `k` levels is a set of `k-1` functionally independent linear combinations of the factor level means that are also independent of the sum of the dummy variables. The dummy coding isnβt wrong *per se*. It captures all of the coefficients, but it complicates matters when the model assumes independence of the coefficients such as in ANOVA. Linear regression models do not assume independence of the coefficients and thus dummy coding is often the only coding that is taught in this context.
To have a look at the contrast matrices in Patsy, we will use data from UCLA ATS. First letβs load the data.
Example Data
------------
```
In [1]: import pandas
In [2]: url = 'https://stats.idre.ucla.edu/stat/data/hsb2.csv'
In [3]: hsb2 = pandas.read_csv(url)
```
It will be instructive to look at the mean of the dependent variable, write, for each level of race ((1 = Hispanic, 2 = Asian, 3 = African American and 4 = Caucasian)).
Treatment (Dummy) Coding
------------------------
Dummy coding is likely the most well known coding scheme. It compares each level of the categorical variable to a base reference level. The base reference level is the value of the intercept. It is the default contrast in Patsy for unordered categorical factors. The Treatment contrast matrix for race would be
```
In [4]: from patsy.contrasts import Treatment
In [5]: levels = [1,2,3,4]
In [6]: contrast = Treatment(reference=0).code_without_intercept(levels)
In [7]: print(contrast.matrix)
[[0. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
```
Here we used `reference=0`, which implies that the first level, Hispanic, is the reference category against which the other level effects are measured. As mentioned above, the columns do not sum to zero and are thus not independent of the intercept. To be explicit, letβs look at how this would encode the `race` variable.
```
In [8]: contrast.matrix[hsb2.race-1, :][:20]
Out[8]:
array([[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 1., 0.],
[0., 0., 0.],
[0., 0., 1.],
[0., 1., 0.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 1., 0.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.]])
```
This is a bit of a trick, as the `race` category conveniently maps to zero-based indices. If it does not, this conversion happens under the hood, so this wonβt work in general but nonetheless is a useful exercise to fix ideas. The below illustrates the output using the three contrasts above
```
In [9]: from statsmodels.formula.api import ols
In [10]: mod = ols("write ~ C(race, Treatment)", data=hsb2)
In [11]: res = mod.fit()
In [12]: print(res.summary())
OLS Regression Results
==============================================================================
Dep. Variable: write R-squared: 0.107
Model: OLS Adj. R-squared: 0.093
Method: Least Squares F-statistic: 7.833
Date: Mon, 14 May 2018 Prob (F-statistic): 5.78e-05
Time: 21:46:19 Log-Likelihood: -721.77
No. Observations: 200 AIC: 1452.
Df Residuals: 196 BIC: 1465.
Df Model: 3
Covariance Type: nonrobust
===========================================================================================
coef std err t P>|t| [0.025 0.975]
-------------------------------------------------------------------------------------------
Intercept 46.4583 1.842 25.218 0.000 42.825 50.091
C(race, Treatment)[T.2] 11.5417 3.286 3.512 0.001 5.061 18.022
C(race, Treatment)[T.3] 1.7417 2.732 0.637 0.525 -3.647 7.131
C(race, Treatment)[T.4] 7.5968 1.989 3.820 0.000 3.675 11.519
==============================================================================
Omnibus: 10.487 Durbin-Watson: 1.779
Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031
Skew: -0.551 Prob(JB): 0.00402
Kurtosis: 2.670 Cond. No. 8.25
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
We explicitly gave the contrast for race; however, since Treatment is the default, we could have omitted this.
Simple Coding
-------------
Like Treatment Coding, Simple Coding compares each level to a fixed reference level. However, with simple coding, the intercept is the grand mean of all the levels of the factors. See [User-Defined Coding](#user-defined) for how to implement the Simple contrast.
```
In [13]: contrast = Simple().code_without_intercept(levels)
In [14]: print(contrast.matrix)
[[-0.25 -0.25 -0.25]
[ 0.75 -0.25 -0.25]
[-0.25 0.75 -0.25]
[-0.25 -0.25 0.75]]
In [15]: mod = ols("write ~ C(race, Simple)", data=hsb2)
In [16]: res = mod.fit()
In [17]: print(res.summary())
OLS Regression Results
==============================================================================
Dep. Variable: write R-squared: 0.107
Model: OLS Adj. R-squared: 0.093
Method: Least Squares F-statistic: 7.833
Date: Mon, 14 May 2018 Prob (F-statistic): 5.78e-05
Time: 21:46:19 Log-Likelihood: -721.77
No. Observations: 200 AIC: 1452.
Df Residuals: 196 BIC: 1465.
Df Model: 3
Covariance Type: nonrobust
===========================================================================================
coef std err t P>|t| [0.025 0.975]
-------------------------------------------------------------------------------------------
Intercept 51.6784 0.982 52.619 0.000 49.741 53.615
C(race, Simple)[Simp.1] 11.5417 3.286 3.512 0.001 5.061 18.022
C(race, Simple)[Simp.2] 1.7417 2.732 0.637 0.525 -3.647 7.131
C(race, Simple)[Simp.3] 7.5968 1.989 3.820 0.000 3.675 11.519
==============================================================================
Omnibus: 10.487 Durbin-Watson: 1.779
Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031
Skew: -0.551 Prob(JB): 0.00402
Kurtosis: 2.670 Cond. No. 7.03
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
Sum (Deviation) Coding
----------------------
Sum coding compares the mean of the dependent variable for a given level to the overall mean of the dependent variable over all the levels. That is, it uses contrasts between each of the first k-1 levels and level k In this example, level 1 is compared to all the others, level 2 to all the others, and level 3 to all the others.
```
In [18]: from patsy.contrasts import Sum
In [19]: contrast = Sum().code_without_intercept(levels)
In [20]: print(contrast.matrix)
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]
[-1. -1. -1.]]
In [21]: mod = ols("write ~ C(race, Sum)", data=hsb2)
In [22]: res = mod.fit()
In [23]: print(res.summary())
OLS Regression Results
==============================================================================
Dep. Variable: write R-squared: 0.107
Model: OLS Adj. R-squared: 0.093
Method: Least Squares F-statistic: 7.833
Date: Mon, 14 May 2018 Prob (F-statistic): 5.78e-05
Time: 21:46:19 Log-Likelihood: -721.77
No. Observations: 200 AIC: 1452.
Df Residuals: 196 BIC: 1465.
Df Model: 3
Covariance Type: nonrobust
=====================================================================================
coef std err t P>|t| [0.025 0.975]
-------------------------------------------------------------------------------------
Intercept 51.6784 0.982 52.619 0.000 49.741 53.615
C(race, Sum)[S.1] -5.2200 1.631 -3.200 0.002 -8.437 -2.003
C(race, Sum)[S.2] 6.3216 2.160 2.926 0.004 2.061 10.582
C(race, Sum)[S.3] -3.4784 1.732 -2.008 0.046 -6.895 -0.062
==============================================================================
Omnibus: 10.487 Durbin-Watson: 1.779
Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031
Skew: -0.551 Prob(JB): 0.00402
Kurtosis: 2.670 Cond. No. 6.72
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
This correspons to a parameterization that forces all the coefficients to sum to zero. Notice that the intercept here is the grand mean where the grand mean is the mean of means of the dependent variable by each level.
```
In [24]: hsb2.groupby('race')['write'].mean().mean()
Out[24]: 51.67837643678162
```
Backward Difference Coding
--------------------------
In backward difference coding, the mean of the dependent variable for a level is compared with the mean of the dependent variable for the prior level. This type of coding may be useful for a nominal or an ordinal variable.
```
In [25]: from patsy.contrasts import Diff
In [26]: contrast = Diff().code_without_intercept(levels)
In [27]: print(contrast.matrix)
[[-0.75 -0.5 -0.25]
[ 0.25 -0.5 -0.25]
[ 0.25 0.5 -0.25]
[ 0.25 0.5 0.75]]
In [28]: mod = ols("write ~ C(race, Diff)", data=hsb2)
In [29]: res = mod.fit()
In [30]: print(res.summary())
OLS Regression Results
==============================================================================
Dep. Variable: write R-squared: 0.107
Model: OLS Adj. R-squared: 0.093
Method: Least Squares F-statistic: 7.833
Date: Mon, 14 May 2018 Prob (F-statistic): 5.78e-05
Time: 21:46:19 Log-Likelihood: -721.77
No. Observations: 200 AIC: 1452.
Df Residuals: 196 BIC: 1465.
Df Model: 3
Covariance Type: nonrobust
======================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------
Intercept 51.6784 0.982 52.619 0.000 49.741 53.615
C(race, Diff)[D.1] 11.5417 3.286 3.512 0.001 5.061 18.022
C(race, Diff)[D.2] -9.8000 3.388 -2.893 0.004 -16.481 -3.119
C(race, Diff)[D.3] 5.8552 2.153 2.720 0.007 1.610 10.101
==============================================================================
Omnibus: 10.487 Durbin-Watson: 1.779
Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031
Skew: -0.551 Prob(JB): 0.00402
Kurtosis: 2.670 Cond. No. 8.30
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
For example, here the coefficient on level 1 is the mean of `write` at level 2 compared with the mean at level 1. Ie.,
```
In [31]: res.params["C(race, Diff)[D.1]"]
Out[31]: 11.541666666666659
In [32]: hsb2.groupby('race').mean()["write"][2] - \
....: hsb2.groupby('race').mean()["write"][1]
....:
```
statsmodels Fitting models using R-style formulas Fitting models using R-style formulas
=====================================
Since version 0.5.0, `statsmodels` allows users to fit statistical models using R-style formulas. Internally, `statsmodels` uses the [patsy](http://patsy.readthedocs.io/en/latest/) package to convert formulas and data to the matrices that are used in model fitting. The formula framework is quite powerful; this tutorial only scratches the surface. A full description of the formula language can be found in the `patsy` docs:
* [Patsy formula language description](http://patsy.readthedocs.io/en/latest/)
Loading modules and functions
-----------------------------
```
In [1]: import statsmodels.formula.api as smf
In [2]: import numpy as np
In [3]: import pandas
```
Notice that we called `statsmodels.formula.api` instead of the usual `statsmodels.api`. The `formula.api` hosts many of the same functions found in `api` (e.g. OLS, GLM), but it also holds lower case counterparts for most of these models. In general, lower case models accept `formula` and `df` arguments, whereas upper case ones take `endog` and `exog` design matrices. `formula` accepts a string which describes the model in terms of a `patsy` formula. `df` takes a [pandas](http://pandas.pydata.org/) data frame.
`dir(smf)` will print a list of available models.
Formula-compatible models have the following generic call signature: `(formula, data, subset=None, *args, **kwargs)`
OLS regression using formulas
-----------------------------
To begin, we fit the linear model described on the [Getting Started](gettingstarted) page. Download the data, subset columns, and list-wise delete to remove missing observations:
```
In [4]: df = sm.datasets.get_rdataset("Guerry", "HistData").data
In [5]: df = df[['Lottery', 'Literacy', 'Wealth', 'Region']].dropna()
In [6]: df.head()
Out[6]:
Lottery Literacy Wealth Region
0 41 37 73 E
1 38 51 22 N
2 66 13 61 C
3 80 46 76 E
4 79 69 83 E
```
Fit the model:
```
In [7]: mod = smf.ols(formula='Lottery ~ Literacy + Wealth + Region', data=df)
In [8]: res = mod.fit()
In [9]: print(res.summary())
OLS Regression Results
==============================================================================
Dep. Variable: Lottery R-squared: 0.338
Model: OLS Adj. R-squared: 0.287
Method: Least Squares F-statistic: 6.636
Date: Mon, 14 May 2018 Prob (F-statistic): 1.07e-05
Time: 21:46:27 Log-Likelihood: -375.30
No. Observations: 85 AIC: 764.6
Df Residuals: 78 BIC: 781.7
Df Model: 6
Covariance Type: nonrobust
===============================================================================
coef std err t P>|t| [0.025 0.975]
-------------------------------------------------------------------------------
Intercept 38.6517 9.456 4.087 0.000 19.826 57.478
Region[T.E] -15.4278 9.727 -1.586 0.117 -34.793 3.938
Region[T.N] -10.0170 9.260 -1.082 0.283 -28.453 8.419
Region[T.S] -4.5483 7.279 -0.625 0.534 -19.039 9.943
Region[T.W] -10.0913 7.196 -1.402 0.165 -24.418 4.235
Literacy -0.1858 0.210 -0.886 0.378 -0.603 0.232
Wealth 0.4515 0.103 4.390 0.000 0.247 0.656
==============================================================================
Omnibus: 3.049 Durbin-Watson: 1.785
Prob(Omnibus): 0.218 Jarque-Bera (JB): 2.694
Skew: -0.340 Prob(JB): 0.260
Kurtosis: 2.454 Cond. No. 371.
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
Categorical variables
---------------------
Looking at the summary printed above, notice that `patsy` determined that elements of *Region* were text strings, so it treated *Region* as a categorical variable. `patsy`βs default is also to include an intercept, so we automatically dropped one of the *Region* categories.
If *Region* had been an integer variable that we wanted to treat explicitly as categorical, we could have done so by using the `C()` operator:
```
In [10]: res = smf.ols(formula='Lottery ~ Literacy + Wealth + C(Region)', data=df).fit()
In [11]: print(res.params)
Intercept 38.651655
C(Region)[T.E] -15.427785
C(Region)[T.N] -10.016961
C(Region)[T.S] -4.548257
C(Region)[T.W] -10.091276
Literacy -0.185819
Wealth 0.451475
dtype: float64
```
Examples more advanced features `patsy`βs categorical variables function can be found here: [Patsy: Contrast Coding Systems for categorical variables](contrasts)
Operators
---------
We have already seen that β~β separates the left-hand side of the model from the right-hand side, and that β+β adds new columns to the design matrix.
### Removing variables
The β-β sign can be used to remove columns/variables. For instance, we can remove the intercept from a model by:
```
In [12]: res = smf.ols(formula='Lottery ~ Literacy + Wealth + C(Region) -1 ', data=df).fit()
In [13]: print(res.params)
C(Region)[C] 38.651655
C(Region)[E] 23.223870
C(Region)[N] 28.634694
C(Region)[S] 34.103399
C(Region)[W] 28.560379
Literacy -0.185819
Wealth 0.451475
dtype: float64
```
### Multiplicative interactions
β:β adds a new column to the design matrix with the product of the other two columns. β\*β will also include the individual columns that were multiplied together:
```
In [14]: res1 = smf.ols(formula='Lottery ~ Literacy : Wealth - 1', data=df).fit()
In [15]: res2 = smf.ols(formula='Lottery ~ Literacy * Wealth - 1', data=df).fit()
In [16]: print(res1.params)
Literacy:Wealth 0.018176
dtype: float64
In [17]: print(res2.params)
```
| programming_docs |
statsmodels Methods for Survival and Duration Analysis Methods for Survival and Duration Analysis
==========================================
[`statsmodels.duration`](#module-statsmodels.duration "statsmodels.duration: Models for durations") implements several standard methods for working with censored data. These methods are most commonly used when the data consist of durations between an origin time point and the time at which some event of interest occurred. A typical example is a medical study in which the origin is the time at which a subject is diagnosed with some condition, and the event of interest is death (or disease progression, recovery, etc.).
Currently only right-censoring is handled. Right censoring occurs when we know that an event occurred after a given time `t`, but we do not know the exact event time.
Survival function estimation and inference
------------------------------------------
The `statsmodels.api.SurvfuncRight` class can be used to estimate a survival function using data that may be right censored. `SurvfuncRight` implements several inference procedures including confidence intervals for survival distribution quantiles, pointwise and simultaneous confidence bands for the survival function, and plotting procedures. The `duration.survdiff` function provides testing procedures for comparing survival distributions.
Examples
--------
Here we create a `SurvfuncRight` object using data from the `flchain` study, which is available through the R datasets repository. We fit the survival distribution only for the female subjects.
```
import statsmodels.api as sm
data = sm.datasets.get_rdataset("flchain", "survival").data
df = data.loc[data.sex == "F", :]
sf = sm.SurvfuncRight(df["futime"], df["death"])
```
The main features of the fitted survival distribution can be seen by calling the `summary` method:
```
sf.summary().head()
```
We can obtain point estimates and confidence intervals for quantiles of the survival distribution. Since only around 30% of the subjects died during this study, we can only estimate quantiles below the 0.3 probability point:
```
sf.quantile(0.25)
sf.quantile_ci(0.25)
```
To plot a single survival function, call the `plot` method:
```
sf.plot()
```
Since this is a large dataset with a lot of censoring, we may wish to not plot the censoring symbols:
```
fig = sf.plot()
ax = fig.get_axes()[0]
pt = ax.get_lines()[1]
pt.set_visible(False)
```
We can also add a 95% simultaneous confidence band to the plot. Typically these bands only plotted for central part of the distribution.
```
fig = sf.plot()
lcb, ucb = sf.simultaneous_cb()
ax = fig.get_axes()[0]
ax.fill_between(sf.surv_times, lcb, ucb, color='lightgrey')
ax.set_xlim(365, 365*10)
ax.set_ylim(0.7, 1)
ax.set_ylabel("Proportion alive")
ax.set_xlabel("Days since enrollment")
```
Here we plot survival functions for two groups (females and males) on the same axes:
```
gb = data.groupby("sex")
ax = plt.axes()
sexes = []
for g in gb:
sexes.append(g[0])
sf = sm.SurvfuncRight(g[1]["futime"], g[1]["death"])
sf.plot(ax)
li = ax.get_lines()
li[1].set_visible(False)
li[3].set_visible(False)
plt.figlegend((li[0], li[2]), sexes, "center right")
plt.ylim(0.6, 1)
ax.set_ylabel("Proportion alive")
ax.set_xlabel("Days since enrollment")
```
We can formally compare two survival distributions with `survdiff`, which implements several standard nonparametric procedures. The default procedure is the logrank test:
```
stat, pv = sm.duration.survdiff(data.futime, data.death, data.sex)
```
Here are some of the other testing procedures implemented by survdiff:
```
# Fleming-Harrington with p=1, i.e. weight by pooled survival time
stat, pv = sm.duration.survdiff(data.futime, data.death, data.sex, weight_type='fh', fh_p=1)
# Gehan-Breslow, weight by number at risk
stat, pv = sm.duration.survdiff(data.futime, data.death, data.sex, weight_type='gb')
# Tarone-Ware, weight by the square root of the number at risk
stat, pv = sm.duration.survdiff(data.futime, data.death, data.sex, weight_type='tw')
```
Regression methods
------------------
Proportional hazard regression models (βCox modelsβ) are a regression technique for censored data. They allow variation in the time to an event to be explained in terms of covariates, similar to what is done in a linear or generalized linear regression model. These models express the covariate effects in terms of βhazard ratiosβ, meaning the the hazard (instantaneous event rate) is multiplied by a given factor depending on the value of the covariates.
Examples
--------
```
import statsmodels.api as sm
import statsmodels.formula.api as smf
data = sm.datasets.get_rdataset("flchain", "survival").data
del data["chapter"]
data = data.dropna()
data["lam"] = data["lambda"]
data["female"] = (data["sex"] == "F").astype(int)
data["year"] = data["sample.yr"] - min(data["sample.yr"])
status = data["death"].values
mod = smf.phreg("futime ~ 0 + age + female + creatinine + "
"np.sqrt(kappa) + np.sqrt(lam) + year + mgus",
data, status=status, ties="efron")
rslt = mod.fit()
print(rslt.summary())
```
See [Statsmodels Examples](examples/index#statsmodels-examples) for more detailed examples.
There are some notebook examples on the Wiki: [Wiki notebooks for PHReg and Survival Analysis](https://github.com/statsmodels/statsmodels/wiki/Examples#survival-analysis)
### References
References for Cox proportional hazards regression model:
```
T Therneau (1996). Extending the Cox model. Technical report.
http://www.mayo.edu/research/documents/biostat-58pdf/DOC-10027288
G Rodriguez (2005). Non-parametric estimation in survival models.
http://data.princeton.edu/pop509/NonParametricSurvival.pdf
B Gillespie (2006). Checking the assumptions in the Cox proportional
hazards model.
http://www.mwsug.org/proceedings/2006/stats/MWSUG-2006-SD08.pdf
```
Module Reference
----------------
The class for working with survival distributions is:
| | |
| --- | --- |
| [`SurvfuncRight`](generated/statsmodels.duration.survfunc.survfuncright#statsmodels.duration.survfunc.SurvfuncRight "statsmodels.duration.survfunc.SurvfuncRight")(time, status[, entry, title, β¦]) | Estimation and inference for a survival function. |
The proportional hazards regression model class is:
| | |
| --- | --- |
| [`PHReg`](generated/statsmodels.duration.hazard_regression.phreg#statsmodels.duration.hazard_regression.PHReg "statsmodels.duration.hazard_regression.PHReg")(endog, exog[, status, entry, strata, β¦]) | Fit the Cox proportional hazards regression model for right censored data. |
The proportional hazards regression result class is:
| | |
| --- | --- |
| [`PHRegResults`](generated/statsmodels.duration.hazard_regression.phregresults#statsmodels.duration.hazard_regression.PHRegResults "statsmodels.duration.hazard_regression.PHRegResults")(model, params, cov\_params[, β¦]) | Class to contain results of fitting a Cox proportional hazards survival model. |
statsmodels Statistics stats Statistics stats
================
This section collects various statistical tests and tools. Some can be used independently of any models, some are intended as extension to the models and model results.
API Warning: The functions and objects in this category are spread out in various modules and might still be moved around. We expect that in future the statistical tests will return class instances with more informative reporting instead of only the raw numbers.
Residual Diagnostics and Specification Tests
--------------------------------------------
| | |
| --- | --- |
| [`durbin_watson`](generated/statsmodels.stats.stattools.durbin_watson#statsmodels.stats.stattools.durbin_watson "statsmodels.stats.stattools.durbin_watson")(resids[, axis]) | Calculates the Durbin-Watson statistic |
| [`jarque_bera`](generated/statsmodels.stats.stattools.jarque_bera#statsmodels.stats.stattools.jarque_bera "statsmodels.stats.stattools.jarque_bera")(resids[, axis]) | Calculates the Jarque-Bera test for normality |
| [`omni_normtest`](generated/statsmodels.stats.stattools.omni_normtest#statsmodels.stats.stattools.omni_normtest "statsmodels.stats.stattools.omni_normtest")(resids[, axis]) | Omnibus test for normality |
| [`medcouple`](generated/statsmodels.stats.stattools.medcouple#statsmodels.stats.stattools.medcouple "statsmodels.stats.stattools.medcouple")(y[, axis]) | Calculates the medcouple robust measure of skew. |
| [`robust_skewness`](generated/statsmodels.stats.stattools.robust_skewness#statsmodels.stats.stattools.robust_skewness "statsmodels.stats.stattools.robust_skewness")(y[, axis]) | Calculates the four skewness measures in Kim & White |
| [`robust_kurtosis`](generated/statsmodels.stats.stattools.robust_kurtosis#statsmodels.stats.stattools.robust_kurtosis "statsmodels.stats.stattools.robust_kurtosis")(y[, axis, ab, dg, excess]) | Calculates the four kurtosis measures in Kim & White |
| [`expected_robust_kurtosis`](generated/statsmodels.stats.stattools.expected_robust_kurtosis#statsmodels.stats.stattools.expected_robust_kurtosis "statsmodels.stats.stattools.expected_robust_kurtosis")([ab, dg]) | Calculates the expected value of the robust kurtosis measures in Kim and White assuming the data are normally distributed. |
| | |
| --- | --- |
| [`acorr_ljungbox`](generated/statsmodels.stats.diagnostic.acorr_ljungbox#statsmodels.stats.diagnostic.acorr_ljungbox "statsmodels.stats.diagnostic.acorr_ljungbox")(x[, lags, boxpierce]) | Ljung-Box test for no autocorrelation |
| [`acorr_breusch_godfrey`](generated/statsmodels.stats.diagnostic.acorr_breusch_godfrey#statsmodels.stats.diagnostic.acorr_breusch_godfrey "statsmodels.stats.diagnostic.acorr_breusch_godfrey")(results[, nlags, store]) | Breusch Godfrey Lagrange Multiplier tests for residual autocorrelation |
| [`HetGoldfeldQuandt`](generated/statsmodels.stats.diagnostic.hetgoldfeldquandt#statsmodels.stats.diagnostic.HetGoldfeldQuandt "statsmodels.stats.diagnostic.HetGoldfeldQuandt") | test whether variance is the same in 2 subsamples |
| [`het_goldfeldquandt`](generated/statsmodels.stats.diagnostic.het_goldfeldquandt#statsmodels.stats.diagnostic.het_goldfeldquandt "statsmodels.stats.diagnostic.het_goldfeldquandt") | see class docstring |
| [`het_breuschpagan`](generated/statsmodels.stats.diagnostic.het_breuschpagan#statsmodels.stats.diagnostic.het_breuschpagan "statsmodels.stats.diagnostic.het_breuschpagan")(resid, exog\_het) | Breusch-Pagan Lagrange Multiplier test for heteroscedasticity |
| [`het_white`](generated/statsmodels.stats.diagnostic.het_white#statsmodels.stats.diagnostic.het_white "statsmodels.stats.diagnostic.het_white")(resid, exog[, retres]) | Whiteβs Lagrange Multiplier Test for Heteroscedasticity |
| [`het_arch`](generated/statsmodels.stats.diagnostic.het_arch#statsmodels.stats.diagnostic.het_arch "statsmodels.stats.diagnostic.het_arch")(resid[, maxlag, autolag, store, β¦]) | Engleβs Test for Autoregressive Conditional Heteroscedasticity (ARCH) |
| [`linear_harvey_collier`](generated/statsmodels.stats.diagnostic.linear_harvey_collier#statsmodels.stats.diagnostic.linear_harvey_collier "statsmodels.stats.diagnostic.linear_harvey_collier")(res) | Harvey Collier test for linearity |
| [`linear_rainbow`](generated/statsmodels.stats.diagnostic.linear_rainbow#statsmodels.stats.diagnostic.linear_rainbow "statsmodels.stats.diagnostic.linear_rainbow")(res[, frac]) | Rainbow test for linearity |
| [`linear_lm`](generated/statsmodels.stats.diagnostic.linear_lm#statsmodels.stats.diagnostic.linear_lm "statsmodels.stats.diagnostic.linear_lm")(resid, exog[, func]) | Lagrange multiplier test for linearity against functional alternative |
| [`breaks_cusumolsresid`](generated/statsmodels.stats.diagnostic.breaks_cusumolsresid#statsmodels.stats.diagnostic.breaks_cusumolsresid "statsmodels.stats.diagnostic.breaks_cusumolsresid")(olsresidual[, ddof]) | cusum test for parameter stability based on ols residuals |
| [`breaks_hansen`](generated/statsmodels.stats.diagnostic.breaks_hansen#statsmodels.stats.diagnostic.breaks_hansen "statsmodels.stats.diagnostic.breaks_hansen")(olsresults) | test for model stability, breaks in parameters for ols, Hansen 1992 |
| [`recursive_olsresiduals`](generated/statsmodels.stats.diagnostic.recursive_olsresiduals#statsmodels.stats.diagnostic.recursive_olsresiduals "statsmodels.stats.diagnostic.recursive_olsresiduals")(olsresults[, skip, β¦]) | calculate recursive ols with residuals and cusum test statistic |
| [`CompareCox`](generated/statsmodels.stats.diagnostic.comparecox#statsmodels.stats.diagnostic.CompareCox "statsmodels.stats.diagnostic.CompareCox") | Cox Test for non-nested models |
| [`compare_cox`](generated/statsmodels.stats.diagnostic.compare_cox#statsmodels.stats.diagnostic.compare_cox "statsmodels.stats.diagnostic.compare_cox") | Cox Test for non-nested models |
| [`CompareJ`](generated/statsmodels.stats.diagnostic.comparej#statsmodels.stats.diagnostic.CompareJ "statsmodels.stats.diagnostic.CompareJ") | J-Test for comparing non-nested models |
| [`compare_j`](generated/statsmodels.stats.diagnostic.compare_j#statsmodels.stats.diagnostic.compare_j "statsmodels.stats.diagnostic.compare_j") | J-Test for comparing non-nested models |
| [`unitroot_adf`](generated/statsmodels.stats.diagnostic.unitroot_adf#statsmodels.stats.diagnostic.unitroot_adf "statsmodels.stats.diagnostic.unitroot_adf")(x[, maxlag, trendorder, β¦]) | |
| [`normal_ad`](generated/statsmodels.stats.diagnostic.normal_ad#statsmodels.stats.diagnostic.normal_ad "statsmodels.stats.diagnostic.normal_ad")(x[, axis]) | Anderson-Darling test for normal distribution unknown mean and variance |
| [`kstest_normal`](generated/statsmodels.stats.diagnostic.kstest_normal#statsmodels.stats.diagnostic.kstest_normal "statsmodels.stats.diagnostic.kstest_normal")(x[, dist, pvalmethod]) | Lilliefors test for normality or an exponential distribution. |
| [`lilliefors`](generated/statsmodels.stats.diagnostic.lilliefors#statsmodels.stats.diagnostic.lilliefors "statsmodels.stats.diagnostic.lilliefors")(x[, dist, pvalmethod]) | Lilliefors test for normality or an exponential distribution. |
### Outliers and influence measures
| | |
| --- | --- |
| [`OLSInfluence`](generated/statsmodels.stats.outliers_influence.olsinfluence#statsmodels.stats.outliers_influence.OLSInfluence "statsmodels.stats.outliers_influence.OLSInfluence")(results) | class to calculate outlier and influence measures for OLS result |
| [`variance_inflation_factor`](generated/statsmodels.stats.outliers_influence.variance_inflation_factor#statsmodels.stats.outliers_influence.variance_inflation_factor "statsmodels.stats.outliers_influence.variance_inflation_factor")(exog, exog\_idx) | variance inflation factor, VIF, for one exogenous variable |
See also the notes on [notes on regression diagnostics](diagnostic#diagnostics)
Sandwich Robust Covariances
---------------------------
The following functions calculate covariance matrices and standard errors for the parameter estimates that are robust to heteroscedasticity and autocorrelation in the errors. Similar to the methods that are available for the LinearModelResults, these methods are designed for use with OLS.
| | |
| --- | --- |
| [`sandwich_covariance.cov_hac`](generated/statsmodels.stats.sandwich_covariance.cov_hac#statsmodels.stats.sandwich_covariance.cov_hac "statsmodels.stats.sandwich_covariance.cov_hac")(results[, β¦]) | heteroscedasticity and autocorrelation robust covariance matrix (Newey-West) |
| [`sandwich_covariance.cov_nw_panel`](generated/statsmodels.stats.sandwich_covariance.cov_nw_panel#statsmodels.stats.sandwich_covariance.cov_nw_panel "statsmodels.stats.sandwich_covariance.cov_nw_panel")(results, β¦) | Panel HAC robust covariance matrix |
| [`sandwich_covariance.cov_nw_groupsum`](generated/statsmodels.stats.sandwich_covariance.cov_nw_groupsum#statsmodels.stats.sandwich_covariance.cov_nw_groupsum "statsmodels.stats.sandwich_covariance.cov_nw_groupsum")(results, β¦) | Driscoll and Kraay Panel robust covariance matrix |
| [`sandwich_covariance.cov_cluster`](generated/statsmodels.stats.sandwich_covariance.cov_cluster#statsmodels.stats.sandwich_covariance.cov_cluster "statsmodels.stats.sandwich_covariance.cov_cluster")(results, group) | cluster robust covariance matrix |
| [`sandwich_covariance.cov_cluster_2groups`](generated/statsmodels.stats.sandwich_covariance.cov_cluster_2groups#statsmodels.stats.sandwich_covariance.cov_cluster_2groups "statsmodels.stats.sandwich_covariance.cov_cluster_2groups")(β¦) | cluster robust covariance matrix for two groups/clusters |
| [`sandwich_covariance.cov_white_simple`](generated/statsmodels.stats.sandwich_covariance.cov_white_simple#statsmodels.stats.sandwich_covariance.cov_white_simple "statsmodels.stats.sandwich_covariance.cov_white_simple")(results) | heteroscedasticity robust covariance matrix (White) |
The following are standalone versions of the heteroscedasticity robust standard errors attached to LinearModelResults
| | |
| --- | --- |
| [`sandwich_covariance.cov_hc0`](generated/statsmodels.stats.sandwich_covariance.cov_hc0#statsmodels.stats.sandwich_covariance.cov_hc0 "statsmodels.stats.sandwich_covariance.cov_hc0")(results) | See statsmodels.RegressionResults |
| [`sandwich_covariance.cov_hc1`](generated/statsmodels.stats.sandwich_covariance.cov_hc1#statsmodels.stats.sandwich_covariance.cov_hc1 "statsmodels.stats.sandwich_covariance.cov_hc1")(results) | See statsmodels.RegressionResults |
| [`sandwich_covariance.cov_hc2`](generated/statsmodels.stats.sandwich_covariance.cov_hc2#statsmodels.stats.sandwich_covariance.cov_hc2 "statsmodels.stats.sandwich_covariance.cov_hc2")(results) | See statsmodels.RegressionResults |
| [`sandwich_covariance.cov_hc3`](generated/statsmodels.stats.sandwich_covariance.cov_hc3#statsmodels.stats.sandwich_covariance.cov_hc3 "statsmodels.stats.sandwich_covariance.cov_hc3")(results) | See statsmodels.RegressionResults |
| [`sandwich_covariance.se_cov`](generated/statsmodels.stats.sandwich_covariance.se_cov#statsmodels.stats.sandwich_covariance.se_cov "statsmodels.stats.sandwich_covariance.se_cov")(cov) | get standard deviation from covariance matrix |
Goodness of Fit Tests and Measures
----------------------------------
some tests for goodness of fit for univariate distributions
| | |
| --- | --- |
| [`powerdiscrepancy`](generated/statsmodels.stats.gof.powerdiscrepancy#statsmodels.stats.gof.powerdiscrepancy "statsmodels.stats.gof.powerdiscrepancy")(observed, expected[, β¦]) | Calculates power discrepancy, a class of goodness-of-fit tests as a measure of discrepancy between observed and expected data. |
| [`gof_chisquare_discrete`](generated/statsmodels.stats.gof.gof_chisquare_discrete#statsmodels.stats.gof.gof_chisquare_discrete "statsmodels.stats.gof.gof_chisquare_discrete")(distfn, arg, rvs, β¦) | perform chisquare test for random sample of a discrete distribution |
| [`gof_binning_discrete`](generated/statsmodels.stats.gof.gof_binning_discrete#statsmodels.stats.gof.gof_binning_discrete "statsmodels.stats.gof.gof_binning_discrete")(rvs, distfn, arg[, nsupp]) | get bins for chisquare type gof tests for a discrete distribution |
| [`chisquare_effectsize`](generated/statsmodels.stats.gof.chisquare_effectsize#statsmodels.stats.gof.chisquare_effectsize "statsmodels.stats.gof.chisquare_effectsize")(probs0, probs1[, β¦]) | effect size for a chisquare goodness-of-fit test |
| | |
| --- | --- |
| [`normal_ad`](generated/statsmodels.stats.diagnostic.normal_ad#statsmodels.stats.diagnostic.normal_ad "statsmodels.stats.diagnostic.normal_ad")(x[, axis]) | Anderson-Darling test for normal distribution unknown mean and variance |
| [`kstest_normal`](generated/statsmodels.stats.diagnostic.kstest_normal#statsmodels.stats.diagnostic.kstest_normal "statsmodels.stats.diagnostic.kstest_normal")(x[, dist, pvalmethod]) | Lilliefors test for normality or an exponential distribution. |
| [`lilliefors`](generated/statsmodels.stats.diagnostic.lilliefors#statsmodels.stats.diagnostic.lilliefors "statsmodels.stats.diagnostic.lilliefors")(x[, dist, pvalmethod]) | Lilliefors test for normality or an exponential distribution. |
Non-Parametric Tests
--------------------
| | |
| --- | --- |
| [`mcnemar`](generated/statsmodels.sandbox.stats.runs.mcnemar#statsmodels.sandbox.stats.runs.mcnemar "statsmodels.sandbox.stats.runs.mcnemar")(x[, y, exact, correction]) | McNemar test |
| [`symmetry_bowker`](generated/statsmodels.sandbox.stats.runs.symmetry_bowker#statsmodels.sandbox.stats.runs.symmetry_bowker "statsmodels.sandbox.stats.runs.symmetry_bowker")(table) | Test for symmetry of a (k, k) square contingency table |
| [`median_test_ksample`](generated/statsmodels.sandbox.stats.runs.median_test_ksample#statsmodels.sandbox.stats.runs.median_test_ksample "statsmodels.sandbox.stats.runs.median_test_ksample")(x, groups) | chisquare test for equality of median/location |
| [`runstest_1samp`](generated/statsmodels.sandbox.stats.runs.runstest_1samp#statsmodels.sandbox.stats.runs.runstest_1samp "statsmodels.sandbox.stats.runs.runstest_1samp")(x[, cutoff, correction]) | use runs test on binary discretized data above/below cutoff |
| [`runstest_2samp`](generated/statsmodels.sandbox.stats.runs.runstest_2samp#statsmodels.sandbox.stats.runs.runstest_2samp "statsmodels.sandbox.stats.runs.runstest_2samp")(x[, y, groups, correction]) | Wald-Wolfowitz runstest for two samples |
| [`cochrans_q`](generated/statsmodels.sandbox.stats.runs.cochrans_q#statsmodels.sandbox.stats.runs.cochrans_q "statsmodels.sandbox.stats.runs.cochrans_q")(x) | Cochranβs Q test for identical effect of k treatments |
| [`Runs`](generated/statsmodels.sandbox.stats.runs.runs#statsmodels.sandbox.stats.runs.Runs "statsmodels.sandbox.stats.runs.Runs")(x) | class for runs in a binary sequence |
| | |
| --- | --- |
| [`sign_test`](generated/statsmodels.stats.descriptivestats.sign_test#statsmodels.stats.descriptivestats.sign_test "statsmodels.stats.descriptivestats.sign_test")(samp[, mu0]) | Signs test. |
Interrater Reliability and Agreement
------------------------------------
The main function that statsmodels has currently available for interrater agreement measures and tests is Cohenβs Kappa. Fleissβ Kappa is currently only implemented as a measures but without associated results statistics.
| | |
| --- | --- |
| [`cohens_kappa`](generated/statsmodels.stats.inter_rater.cohens_kappa#statsmodels.stats.inter_rater.cohens_kappa "statsmodels.stats.inter_rater.cohens_kappa")(table[, weights, β¦]) | Compute Cohenβs kappa with variance and equal-zero test |
| [`fleiss_kappa`](generated/statsmodels.stats.inter_rater.fleiss_kappa#statsmodels.stats.inter_rater.fleiss_kappa "statsmodels.stats.inter_rater.fleiss_kappa")(table[, method]) | Fleissβ and Randolphβs kappa multi-rater agreement measure |
| [`to_table`](generated/statsmodels.stats.inter_rater.to_table#statsmodels.stats.inter_rater.to_table "statsmodels.stats.inter_rater.to_table")(data[, bins]) | convert raw data with shape (subject, rater) to (rater1, rater2) |
| [`aggregate_raters`](generated/statsmodels.stats.inter_rater.aggregate_raters#statsmodels.stats.inter_rater.aggregate_raters "statsmodels.stats.inter_rater.aggregate_raters")(data[, n\_cat]) | convert raw data with shape (subject, rater) to (subject, cat\_counts) |
Multiple Tests and Multiple Comparison Procedures
-------------------------------------------------
`multipletests` is a function for p-value correction, which also includes p-value correction based on fdr in `fdrcorrection`. `tukeyhsd` performs simultaneous testing for the comparison of (independent) means. These three functions are verified. GroupsStats and MultiComparison are convenience classes to multiple comparisons similar to one way ANOVA, but still in developement
| | |
| --- | --- |
| [`multipletests`](generated/statsmodels.stats.multitest.multipletests#statsmodels.stats.multitest.multipletests "statsmodels.stats.multitest.multipletests")(pvals[, alpha, method, β¦]) | Test results and p-value correction for multiple tests |
| [`fdrcorrection`](generated/statsmodels.stats.multitest.fdrcorrection#statsmodels.stats.multitest.fdrcorrection "statsmodels.stats.multitest.fdrcorrection")(pvals[, alpha, method, is\_sorted]) | pvalue correction for false discovery rate |
| | |
| --- | --- |
| [`GroupsStats`](generated/statsmodels.sandbox.stats.multicomp.groupsstats#statsmodels.sandbox.stats.multicomp.GroupsStats "statsmodels.sandbox.stats.multicomp.GroupsStats")(x[, useranks, uni, intlab]) | statistics by groups (another version) |
| [`MultiComparison`](generated/statsmodels.sandbox.stats.multicomp.multicomparison#statsmodels.sandbox.stats.multicomp.MultiComparison "statsmodels.sandbox.stats.multicomp.MultiComparison")(data, groups[, group\_order]) | Tests for multiple comparisons |
| [`TukeyHSDResults`](generated/statsmodels.sandbox.stats.multicomp.tukeyhsdresults#statsmodels.sandbox.stats.multicomp.TukeyHSDResults "statsmodels.sandbox.stats.multicomp.TukeyHSDResults")(mc\_object, results\_table, q\_crit) | Results from Tukey HSD test, with additional plot methods |
| | |
| --- | --- |
| [`pairwise_tukeyhsd`](generated/statsmodels.stats.multicomp.pairwise_tukeyhsd#statsmodels.stats.multicomp.pairwise_tukeyhsd "statsmodels.stats.multicomp.pairwise_tukeyhsd")(endog, groups[, alpha]) | calculate all pairwise comparisons with TukeyHSD confidence intervals |
| | |
| --- | --- |
| [`local_fdr`](generated/statsmodels.stats.multitest.local_fdr#statsmodels.stats.multitest.local_fdr "statsmodels.stats.multitest.local_fdr")(zscores[, null\_proportion, β¦]) | Calculate local FDR values for a list of Z-scores. |
| [`fdrcorrection_twostage`](generated/statsmodels.stats.multitest.fdrcorrection_twostage#statsmodels.stats.multitest.fdrcorrection_twostage "statsmodels.stats.multitest.fdrcorrection_twostage")(pvals[, alpha, β¦]) | (iterated) two stage linear step-up procedure with estimation of number of true hypotheses |
| [`NullDistribution`](generated/statsmodels.stats.multitest.nulldistribution#statsmodels.stats.multitest.NullDistribution "statsmodels.stats.multitest.NullDistribution")(zscores[, null\_lb, β¦]) | Estimate a Gaussian distribution for the null Z-scores. |
| [`RegressionFDR`](generated/statsmodels.stats.multitest.regressionfdr#statsmodels.stats.multitest.RegressionFDR "statsmodels.stats.multitest.RegressionFDR")(endog, exog, regeffects[, method]) | Control FDR in a regression procedure. |
The following functions are not (yet) public
| | |
| --- | --- |
| [`varcorrection_pairs_unbalanced`](generated/statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unbalanced#statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unbalanced "statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unbalanced")(nobs\_all[, β¦]) | correction factor for variance with unequal sample sizes for all pairs |
| [`varcorrection_pairs_unequal`](generated/statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unequal#statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unequal "statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unequal")(var\_all, β¦) | return joint variance from samples with unequal variances and unequal sample sizes for all pairs |
| [`varcorrection_unbalanced`](generated/statsmodels.sandbox.stats.multicomp.varcorrection_unbalanced#statsmodels.sandbox.stats.multicomp.varcorrection_unbalanced "statsmodels.sandbox.stats.multicomp.varcorrection_unbalanced")(nobs\_all[, srange]) | correction factor for variance with unequal sample sizes |
| [`varcorrection_unequal`](generated/statsmodels.sandbox.stats.multicomp.varcorrection_unequal#statsmodels.sandbox.stats.multicomp.varcorrection_unequal "statsmodels.sandbox.stats.multicomp.varcorrection_unequal")(var\_all, nobs\_all, df\_all) | return joint variance from samples with unequal variances and unequal sample sizes |
| [`StepDown`](generated/statsmodels.sandbox.stats.multicomp.stepdown#statsmodels.sandbox.stats.multicomp.StepDown "statsmodels.sandbox.stats.multicomp.StepDown")(vals, nobs\_all, var\_all[, df]) | a class for step down methods |
| [`catstack`](generated/statsmodels.sandbox.stats.multicomp.catstack#statsmodels.sandbox.stats.multicomp.catstack "statsmodels.sandbox.stats.multicomp.catstack")(args) | |
| [`ccols`](generated/statsmodels.sandbox.stats.multicomp.ccols#statsmodels.sandbox.stats.multicomp.ccols "statsmodels.sandbox.stats.multicomp.ccols") | |
| [`compare_ordered`](generated/statsmodels.sandbox.stats.multicomp.compare_ordered#statsmodels.sandbox.stats.multicomp.compare_ordered "statsmodels.sandbox.stats.multicomp.compare_ordered")(vals, alpha) | simple ordered sequential comparison of means |
| [`distance_st_range`](generated/statsmodels.sandbox.stats.multicomp.distance_st_range#statsmodels.sandbox.stats.multicomp.distance_st_range "statsmodels.sandbox.stats.multicomp.distance_st_range")(mean\_all, nobs\_all, var\_all) | pairwise distance matrix, outsourced from tukeyhsd |
| [`ecdf`](generated/statsmodels.sandbox.stats.multicomp.ecdf#statsmodels.sandbox.stats.multicomp.ecdf "statsmodels.sandbox.stats.multicomp.ecdf")(x) | no frills empirical cdf used in fdrcorrection |
| [`get_tukeyQcrit`](generated/statsmodels.sandbox.stats.multicomp.get_tukeyqcrit#statsmodels.sandbox.stats.multicomp.get_tukeyQcrit "statsmodels.sandbox.stats.multicomp.get_tukeyQcrit")(k, df[, alpha]) | return critical values for Tukeyβs HSD (Q) |
| [`homogeneous_subsets`](generated/statsmodels.sandbox.stats.multicomp.homogeneous_subsets#statsmodels.sandbox.stats.multicomp.homogeneous_subsets "statsmodels.sandbox.stats.multicomp.homogeneous_subsets")(vals, dcrit) | recursively check all pairs of vals for minimum distance |
| [`maxzero`](generated/statsmodels.sandbox.stats.multicomp.maxzero#statsmodels.sandbox.stats.multicomp.maxzero "statsmodels.sandbox.stats.multicomp.maxzero")(x) | find all up zero crossings and return the index of the highest |
| [`maxzerodown`](generated/statsmodels.sandbox.stats.multicomp.maxzerodown#statsmodels.sandbox.stats.multicomp.maxzerodown "statsmodels.sandbox.stats.multicomp.maxzerodown")(x) | find all up zero crossings and return the index of the highest |
| [`mcfdr`](generated/statsmodels.sandbox.stats.multicomp.mcfdr#statsmodels.sandbox.stats.multicomp.mcfdr "statsmodels.sandbox.stats.multicomp.mcfdr")([nrepl, nobs, ntests, ntrue, mu, β¦]) | MonteCarlo to test fdrcorrection |
| [`qcrit`](generated/statsmodels.sandbox.stats.multicomp.qcrit#statsmodels.sandbox.stats.multicomp.qcrit "statsmodels.sandbox.stats.multicomp.qcrit") | str(object=ββ) -> str str(bytes\_or\_buffer[, encoding[, errors]]) -> str |
| [`randmvn`](generated/statsmodels.sandbox.stats.multicomp.randmvn#statsmodels.sandbox.stats.multicomp.randmvn "statsmodels.sandbox.stats.multicomp.randmvn")(rho[, size, standardize]) | create random draws from equi-correlated multivariate normal distribution |
| [`rankdata`](generated/statsmodels.sandbox.stats.multicomp.rankdata#statsmodels.sandbox.stats.multicomp.rankdata "statsmodels.sandbox.stats.multicomp.rankdata")(x) | rankdata, equivalent to scipy.stats.rankdata |
| [`rejectionline`](generated/statsmodels.sandbox.stats.multicomp.rejectionline#statsmodels.sandbox.stats.multicomp.rejectionline "statsmodels.sandbox.stats.multicomp.rejectionline")(n[, alpha]) | reference line for rejection in multiple tests |
| [`set_partition`](generated/statsmodels.sandbox.stats.multicomp.set_partition#statsmodels.sandbox.stats.multicomp.set_partition "statsmodels.sandbox.stats.multicomp.set_partition")(ssli) | extract a partition from a list of tuples |
| [`set_remove_subs`](generated/statsmodels.sandbox.stats.multicomp.set_remove_subs#statsmodels.sandbox.stats.multicomp.set_remove_subs "statsmodels.sandbox.stats.multicomp.set_remove_subs")(ssli) | remove sets that are subsets of another set from a list of tuples |
| [`tiecorrect`](generated/statsmodels.sandbox.stats.multicomp.tiecorrect#statsmodels.sandbox.stats.multicomp.tiecorrect "statsmodels.sandbox.stats.multicomp.tiecorrect")(xranks) | should be equivalent of scipy.stats.tiecorrect |
Basic Statistics and t-Tests with frequency weights
---------------------------------------------------
Besides basic statistics, like mean, variance, covariance and correlation for data with case weights, the classes here provide one and two sample tests for means. The t-tests have more options than those in scipy.stats, but are more restrictive in the shape of the arrays. Confidence intervals for means are provided based on the same assumptions as the t-tests.
Additionally, tests for equivalence of means are available for one sample and for two, either paired or independent, samples. These tests are based on TOST, two one-sided tests, which have as null hypothesis that the means are not βcloseβ to each other.
| | |
| --- | --- |
| [`DescrStatsW`](generated/statsmodels.stats.weightstats.descrstatsw#statsmodels.stats.weightstats.DescrStatsW "statsmodels.stats.weightstats.DescrStatsW")(data[, weights, ddof]) | descriptive statistics and tests with weights for case weights |
| [`CompareMeans`](generated/statsmodels.stats.weightstats.comparemeans#statsmodels.stats.weightstats.CompareMeans "statsmodels.stats.weightstats.CompareMeans")(d1, d2) | class for two sample comparison |
| [`ttest_ind`](generated/statsmodels.stats.weightstats.ttest_ind#statsmodels.stats.weightstats.ttest_ind "statsmodels.stats.weightstats.ttest_ind")(x1, x2[, alternative, usevar, β¦]) | ttest independent sample |
| [`ttost_ind`](generated/statsmodels.stats.weightstats.ttost_ind#statsmodels.stats.weightstats.ttost_ind "statsmodels.stats.weightstats.ttost_ind")(x1, x2, low, upp[, usevar, β¦]) | test of (non-)equivalence for two independent samples |
| [`ttost_paired`](generated/statsmodels.stats.weightstats.ttost_paired#statsmodels.stats.weightstats.ttost_paired "statsmodels.stats.weightstats.ttost_paired")(x1, x2, low, upp[, transform, β¦]) | test of (non-)equivalence for two dependent, paired sample |
| [`ztest`](generated/statsmodels.stats.weightstats.ztest#statsmodels.stats.weightstats.ztest "statsmodels.stats.weightstats.ztest")(x1[, x2, value, alternative, usevar, ddof]) | test for mean based on normal distribution, one or two samples |
| [`ztost`](generated/statsmodels.stats.weightstats.ztost#statsmodels.stats.weightstats.ztost "statsmodels.stats.weightstats.ztost")(x1, low, upp[, x2, usevar, ddof]) | Equivalence test based on normal distribution |
| [`zconfint`](generated/statsmodels.stats.weightstats.zconfint#statsmodels.stats.weightstats.zconfint "statsmodels.stats.weightstats.zconfint")(x1[, x2, value, alpha, β¦]) | confidence interval based on normal distribution z-test |
weightstats also contains tests and confidence intervals based on summary data
| | |
| --- | --- |
| [`_tconfint_generic`](generated/statsmodels.stats.weightstats._tconfint_generic#statsmodels.stats.weightstats._tconfint_generic "statsmodels.stats.weightstats._tconfint_generic")(mean, std\_mean, dof, β¦) | generic t-confint to save typing |
| [`_tstat_generic`](generated/statsmodels.stats.weightstats._tstat_generic#statsmodels.stats.weightstats._tstat_generic "statsmodels.stats.weightstats._tstat_generic")(value1, value2, std\_diff, β¦) | generic ttest to save typing |
| [`_zconfint_generic`](generated/statsmodels.stats.weightstats._zconfint_generic#statsmodels.stats.weightstats._zconfint_generic "statsmodels.stats.weightstats._zconfint_generic")(mean, std\_mean, alpha, β¦) | generic normal-confint to save typing |
| [`_zstat_generic`](generated/statsmodels.stats.weightstats._zstat_generic#statsmodels.stats.weightstats._zstat_generic "statsmodels.stats.weightstats._zstat_generic")(value1, value2, std\_diff, β¦) | generic (normal) z-test to save typing |
| [`_zstat_generic2`](generated/statsmodels.stats.weightstats._zstat_generic2#statsmodels.stats.weightstats._zstat_generic2 "statsmodels.stats.weightstats._zstat_generic2")(value, std\_diff, alternative) | generic (normal) z-test to save typing |
Power and Sample Size Calculations
----------------------------------
The `power` module currently implements power and sample size calculations for the t-tests, normal based test, F-tests and Chisquare goodness of fit test. The implementation is class based, but the module also provides three shortcut functions, `tt_solve_power`, `tt_ind_solve_power` and `zt_ind_solve_power` to solve for any one of the parameters of the power equations.
| | |
| --- | --- |
| [`TTestIndPower`](generated/statsmodels.stats.power.ttestindpower#statsmodels.stats.power.TTestIndPower "statsmodels.stats.power.TTestIndPower")(\*\*kwds) | Statistical Power calculations for t-test for two independent sample |
| [`TTestPower`](generated/statsmodels.stats.power.ttestpower#statsmodels.stats.power.TTestPower "statsmodels.stats.power.TTestPower")(\*\*kwds) | Statistical Power calculations for one sample or paired sample t-test |
| [`GofChisquarePower`](generated/statsmodels.stats.power.gofchisquarepower#statsmodels.stats.power.GofChisquarePower "statsmodels.stats.power.GofChisquarePower")(\*\*kwds) | Statistical Power calculations for one sample chisquare test |
| [`NormalIndPower`](generated/statsmodels.stats.power.normalindpower#statsmodels.stats.power.NormalIndPower "statsmodels.stats.power.NormalIndPower")([ddof]) | Statistical Power calculations for z-test for two independent samples. |
| [`FTestAnovaPower`](generated/statsmodels.stats.power.ftestanovapower#statsmodels.stats.power.FTestAnovaPower "statsmodels.stats.power.FTestAnovaPower")(\*\*kwds) | Statistical Power calculations F-test for one factor balanced ANOVA |
| [`FTestPower`](generated/statsmodels.stats.power.ftestpower#statsmodels.stats.power.FTestPower "statsmodels.stats.power.FTestPower")(\*\*kwds) | Statistical Power calculations for generic F-test |
| [`tt_solve_power`](generated/statsmodels.stats.power.tt_solve_power#statsmodels.stats.power.tt_solve_power "statsmodels.stats.power.tt_solve_power") | solve for any one parameter of the power of a one sample t-test |
| [`tt_ind_solve_power`](generated/statsmodels.stats.power.tt_ind_solve_power#statsmodels.stats.power.tt_ind_solve_power "statsmodels.stats.power.tt_ind_solve_power") | solve for any one parameter of the power of a two sample t-test |
| [`zt_ind_solve_power`](generated/statsmodels.stats.power.zt_ind_solve_power#statsmodels.stats.power.zt_ind_solve_power "statsmodels.stats.power.zt_ind_solve_power") | solve for any one parameter of the power of a two sample z-test |
Proportion
----------
Also available are hypothesis test, confidence intervals and effect size for proportions that can be used with NormalIndPower.
| | |
| --- | --- |
| [`proportion_confint`](generated/statsmodels.stats.proportion.proportion_confint#statsmodels.stats.proportion.proportion_confint "statsmodels.stats.proportion.proportion_confint")(count, nobs[, alpha, method]) | confidence interval for a binomial proportion |
| [`proportion_effectsize`](generated/statsmodels.stats.proportion.proportion_effectsize#statsmodels.stats.proportion.proportion_effectsize "statsmodels.stats.proportion.proportion_effectsize")(prop1, prop2[, method]) | effect size for a test comparing two proportions |
| [`binom_test`](generated/statsmodels.stats.proportion.binom_test#statsmodels.stats.proportion.binom_test "statsmodels.stats.proportion.binom_test")(count, nobs[, prop, alternative]) | Perform a test that the probability of success is p. |
| [`binom_test_reject_interval`](generated/statsmodels.stats.proportion.binom_test_reject_interval#statsmodels.stats.proportion.binom_test_reject_interval "statsmodels.stats.proportion.binom_test_reject_interval")(value, nobs[, β¦]) | rejection region for binomial test for one sample proportion |
| [`binom_tost`](generated/statsmodels.stats.proportion.binom_tost#statsmodels.stats.proportion.binom_tost "statsmodels.stats.proportion.binom_tost")(count, nobs, low, upp) | exact TOST test for one proportion using binomial distribution |
| [`binom_tost_reject_interval`](generated/statsmodels.stats.proportion.binom_tost_reject_interval#statsmodels.stats.proportion.binom_tost_reject_interval "statsmodels.stats.proportion.binom_tost_reject_interval")(low, upp, nobs[, β¦]) | rejection region for binomial TOST |
| [`multinomial_proportions_confint`](generated/statsmodels.stats.proportion.multinomial_proportions_confint#statsmodels.stats.proportion.multinomial_proportions_confint "statsmodels.stats.proportion.multinomial_proportions_confint")(counts[, β¦]) | Confidence intervals for multinomial proportions. |
| [`proportions_ztest`](generated/statsmodels.stats.proportion.proportions_ztest#statsmodels.stats.proportion.proportions_ztest "statsmodels.stats.proportion.proportions_ztest")(count, nobs[, value, β¦]) | Test for proportions based on normal (z) test |
| [`proportions_ztost`](generated/statsmodels.stats.proportion.proportions_ztost#statsmodels.stats.proportion.proportions_ztost "statsmodels.stats.proportion.proportions_ztost")(count, nobs, low, upp[, β¦]) | Equivalence test based on normal distribution |
| [`proportions_chisquare`](generated/statsmodels.stats.proportion.proportions_chisquare#statsmodels.stats.proportion.proportions_chisquare "statsmodels.stats.proportion.proportions_chisquare")(count, nobs[, value]) | test for proportions based on chisquare test |
| [`proportions_chisquare_allpairs`](generated/statsmodels.stats.proportion.proportions_chisquare_allpairs#statsmodels.stats.proportion.proportions_chisquare_allpairs "statsmodels.stats.proportion.proportions_chisquare_allpairs")(count, nobs) | chisquare test of proportions for all pairs of k samples |
| [`proportions_chisquare_pairscontrol`](generated/statsmodels.stats.proportion.proportions_chisquare_pairscontrol#statsmodels.stats.proportion.proportions_chisquare_pairscontrol "statsmodels.stats.proportion.proportions_chisquare_pairscontrol")(count, nobs) | chisquare test of proportions for pairs of k samples compared to control |
| [`proportion_effectsize`](generated/statsmodels.stats.proportion.proportion_effectsize#statsmodels.stats.proportion.proportion_effectsize "statsmodels.stats.proportion.proportion_effectsize")(prop1, prop2[, method]) | effect size for a test comparing two proportions |
| [`power_binom_tost`](generated/statsmodels.stats.proportion.power_binom_tost#statsmodels.stats.proportion.power_binom_tost "statsmodels.stats.proportion.power_binom_tost")(low, upp, nobs[, p\_alt, alpha]) | |
| [`power_ztost_prop`](generated/statsmodels.stats.proportion.power_ztost_prop#statsmodels.stats.proportion.power_ztost_prop "statsmodels.stats.proportion.power_ztost_prop")(low, upp, nobs, p\_alt[, β¦]) | Power of proportions equivalence test based on normal distribution |
| [`samplesize_confint_proportion`](generated/statsmodels.stats.proportion.samplesize_confint_proportion#statsmodels.stats.proportion.samplesize_confint_proportion "statsmodels.stats.proportion.samplesize_confint_proportion")(proportion, β¦) | find sample size to get desired confidence interval length |
Moment Helpers
--------------
When there are missing values, then it is possible that a correlation or covariance matrix is not positive semi-definite. The following three functions can be used to find a correlation or covariance matrix that is positive definite and close to the original matrix.
| | |
| --- | --- |
| [`corr_clipped`](generated/statsmodels.stats.correlation_tools.corr_clipped#statsmodels.stats.correlation_tools.corr_clipped "statsmodels.stats.correlation_tools.corr_clipped")(corr[, threshold]) | Find a near correlation matrix that is positive semi-definite |
| [`corr_nearest`](generated/statsmodels.stats.correlation_tools.corr_nearest#statsmodels.stats.correlation_tools.corr_nearest "statsmodels.stats.correlation_tools.corr_nearest")(corr[, threshold, n\_fact]) | Find the nearest correlation matrix that is positive semi-definite. |
| [`corr_nearest_factor`](generated/statsmodels.stats.correlation_tools.corr_nearest_factor#statsmodels.stats.correlation_tools.corr_nearest_factor "statsmodels.stats.correlation_tools.corr_nearest_factor")(corr, rank[, ctol, β¦]) | Find the nearest correlation matrix with factor structure to a given square matrix. |
| [`corr_thresholded`](generated/statsmodels.stats.correlation_tools.corr_thresholded#statsmodels.stats.correlation_tools.corr_thresholded "statsmodels.stats.correlation_tools.corr_thresholded")(data[, minabs, max\_elt]) | Construct a sparse matrix containing the thresholded row-wise correlation matrix from a data array. |
| [`cov_nearest`](generated/statsmodels.stats.correlation_tools.cov_nearest#statsmodels.stats.correlation_tools.cov_nearest "statsmodels.stats.correlation_tools.cov_nearest")(cov[, method, threshold, β¦]) | Find the nearest covariance matrix that is postive (semi-) definite |
| [`cov_nearest_factor_homog`](generated/statsmodels.stats.correlation_tools.cov_nearest_factor_homog#statsmodels.stats.correlation_tools.cov_nearest_factor_homog "statsmodels.stats.correlation_tools.cov_nearest_factor_homog")(cov, rank) | Approximate an arbitrary square matrix with a factor-structured matrix of the form k\*I + XXβ. |
| [`FactoredPSDMatrix`](generated/statsmodels.stats.correlation_tools.factoredpsdmatrix#statsmodels.stats.correlation_tools.FactoredPSDMatrix "statsmodels.stats.correlation_tools.FactoredPSDMatrix")(diag, root) | Representation of a positive semidefinite matrix in factored form. |
These are utility functions to convert between central and non-central moments, skew, kurtosis and cummulants.
| | |
| --- | --- |
| [`cum2mc`](generated/statsmodels.stats.moment_helpers.cum2mc#statsmodels.stats.moment_helpers.cum2mc "statsmodels.stats.moment_helpers.cum2mc")(kappa) | convert non-central moments to cumulants recursive formula produces as many cumulants as moments |
| [`mc2mnc`](generated/statsmodels.stats.moment_helpers.mc2mnc#statsmodels.stats.moment_helpers.mc2mnc "statsmodels.stats.moment_helpers.mc2mnc")(mc) | convert central to non-central moments, uses recursive formula optionally adjusts first moment to return mean |
| [`mc2mvsk`](generated/statsmodels.stats.moment_helpers.mc2mvsk#statsmodels.stats.moment_helpers.mc2mvsk "statsmodels.stats.moment_helpers.mc2mvsk")(args) | convert central moments to mean, variance, skew, kurtosis |
| [`mnc2cum`](generated/statsmodels.stats.moment_helpers.mnc2cum#statsmodels.stats.moment_helpers.mnc2cum "statsmodels.stats.moment_helpers.mnc2cum")(mnc) | convert non-central moments to cumulants recursive formula produces as many cumulants as moments |
| [`mnc2mc`](generated/statsmodels.stats.moment_helpers.mnc2mc#statsmodels.stats.moment_helpers.mnc2mc "statsmodels.stats.moment_helpers.mnc2mc")(mnc[, wmean]) | convert non-central to central moments, uses recursive formula optionally adjusts first moment to return mean |
| [`mnc2mvsk`](generated/statsmodels.stats.moment_helpers.mnc2mvsk#statsmodels.stats.moment_helpers.mnc2mvsk "statsmodels.stats.moment_helpers.mnc2mvsk")(args) | convert central moments to mean, variance, skew, kurtosis |
| [`mvsk2mc`](generated/statsmodels.stats.moment_helpers.mvsk2mc#statsmodels.stats.moment_helpers.mvsk2mc "statsmodels.stats.moment_helpers.mvsk2mc")(args) | convert mean, variance, skew, kurtosis to central moments |
| [`mvsk2mnc`](generated/statsmodels.stats.moment_helpers.mvsk2mnc#statsmodels.stats.moment_helpers.mvsk2mnc "statsmodels.stats.moment_helpers.mvsk2mnc")(args) | convert mean, variance, skew, kurtosis to non-central moments |
| [`cov2corr`](generated/statsmodels.stats.moment_helpers.cov2corr#statsmodels.stats.moment_helpers.cov2corr "statsmodels.stats.moment_helpers.cov2corr")(cov[, return\_std]) | convert covariance matrix to correlation matrix |
| [`corr2cov`](generated/statsmodels.stats.moment_helpers.corr2cov#statsmodels.stats.moment_helpers.corr2cov "statsmodels.stats.moment_helpers.corr2cov")(corr, std) | convert correlation matrix to covariance matrix given standard deviation |
| [`se_cov`](generated/statsmodels.stats.moment_helpers.se_cov#statsmodels.stats.moment_helpers.se_cov "statsmodels.stats.moment_helpers.se_cov")(cov) | get standard deviation from covariance matrix |
Mediation Analysis
------------------
Mediation analysis focuses on the relationships among three key variables: an βoutcomeβ, a βtreatmentβ, and a βmediatorβ. Since mediation analysis is a form of causal inference, there are several assumptions involved that are difficult or impossible to verify. Ideally, mediation analysis is conducted in the context of an experiment such as this one in which the treatment is randomly assigned. It is also common for people to conduct mediation analyses using observational data in which the treatment may be thought of as an βexposureβ. The assumptions behind mediation analysis are even more difficult to verify in an observational setting.
| | |
| --- | --- |
| [`Mediation`](generated/statsmodels.stats.mediation.mediation#statsmodels.stats.mediation.Mediation "statsmodels.stats.mediation.Mediation")(outcome\_model, mediator\_model, β¦) | Conduct a mediation analysis. |
| [`MediationResults`](generated/statsmodels.stats.mediation.mediationresults#statsmodels.stats.mediation.MediationResults "statsmodels.stats.mediation.MediationResults")(indirect\_effects, β¦) | A class for holding the results of a mediation analysis. |
| programming_docs |
statsmodels Statsmodels Statsmodels
===========
[`statsmodels`](http://www.statsmodels.org/stable/about.html#module-statsmodels "statsmodels: Statistical analysis in Python") is a Python module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration. An extensive list of result statistics are available for each estimator. The results are tested against existing statistical packages to ensure that they are correct. The package is released under the open source Modified BSD (3-clause) license. The online documentation is hosted at [statsmodels.org](http://www.statsmodels.org/).
Minimal Examples
----------------
Since version `0.5.0` of `statsmodels`, you can use R-style formulas together with `pandas` data frames to fit your models. Here is a simple example using ordinary least squares:
```
In [1]: import numpy as np
In [2]: import statsmodels.api as sm
In [3]: import statsmodels.formula.api as smf
# Load data
In [4]: dat = sm.datasets.get_rdataset("Guerry", "HistData").data
# Fit regression model (using the natural log of one of the regressors)
In [5]: results = smf.ols('Lottery ~ Literacy + np.log(Pop1831)', data=dat).fit()
# Inspect the results
In [6]: print(results.summary())
OLS Regression Results
==============================================================================
Dep. Variable: Lottery R-squared: 0.348
Model: OLS Adj. R-squared: 0.333
Method: Least Squares F-statistic: 22.20
Date: Mon, 14 May 2018 Prob (F-statistic): 1.90e-08
Time: 21:48:09 Log-Likelihood: -379.82
No. Observations: 86 AIC: 765.6
Df Residuals: 83 BIC: 773.0
Df Model: 2
Covariance Type: nonrobust
===================================================================================
coef std err t P>|t| [0.025 0.975]
-----------------------------------------------------------------------------------
Intercept 246.4341 35.233 6.995 0.000 176.358 316.510
Literacy -0.4889 0.128 -3.832 0.000 -0.743 -0.235
np.log(Pop1831) -31.3114 5.977 -5.239 0.000 -43.199 -19.424
==============================================================================
Omnibus: 3.713 Durbin-Watson: 2.019
Prob(Omnibus): 0.156 Jarque-Bera (JB): 3.394
Skew: -0.487 Prob(JB): 0.183
Kurtosis: 3.003 Cond. No. 702.
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
You can also use `numpy` arrays instead of formulas:
```
In [7]: import numpy as np
In [8]: import statsmodels.api as sm
# Generate artificial data (2 regressors + constant)
In [9]: nobs = 100
In [10]: X = np.random.random((nobs, 2))
In [11]: X = sm.add_constant(X)
In [12]: beta = [1, .1, .5]
In [13]: e = np.random.random(nobs)
In [14]: y = np.dot(X, beta) + e
# Fit regression model
In [15]: results = sm.OLS(y, X).fit()
# Inspect the results
In [16]: print(results.summary())
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.183
Model: OLS Adj. R-squared: 0.166
Method: Least Squares F-statistic: 10.83
Date: Mon, 14 May 2018 Prob (F-statistic): 5.68e-05
Time: 21:48:10 Log-Likelihood: -23.528
No. Observations: 100 AIC: 53.06
Df Residuals: 97 BIC: 60.87
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 1.4355 0.081 17.716 0.000 1.275 1.596
x1 0.2664 0.101 2.650 0.009 0.067 0.466
x2 0.4224 0.116 3.635 0.000 0.192 0.653
==============================================================================
Omnibus: 75.567 Durbin-Watson: 2.054
Prob(Omnibus): 0.000 Jarque-Bera (JB): 7.752
Skew: 0.065 Prob(JB): 0.0207
Kurtosis: 1.642 Cond. No. 5.32
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
Have a look at `dir(results)` to see available results. Attributes are described in `results.__doc__` and results methods have their own docstrings.
Citation
--------
When using statsmodels in scientific publication, please consider using the following citation:
Seabold, Skipper, and Josef Perktold. β[Statsmodels: Econometric and statistical modeling with python.](http://conference.scipy.org/proceedings/scipy2010/pdfs/seabold.pdf)β *Proceedings of the 9th Python in Science Conference.* 2010. Bibtex entry:
```
@inproceedings{seabold2010statsmodels,
title={Statsmodels: Econometric and statistical modeling with python},
author={Seabold, Skipper and Perktold, Josef},
booktitle={9th Python in Science Conference},
year={2010},
}
```
statsmodels Generalized Method of Moments gmm Generalized Method of Moments gmm
=================================
`statsmodels.gmm` contains model classes and functions that are based on estimation with Generalized Method of Moments. Currently the general non-linear case is implemented. An example class for the standard linear instrumental variable model is included. This has been introduced as a test case, it works correctly but it does not take the linear structure into account. For the linear case we intend to introduce a specific implementation which will be faster and numerically more accurate.
Currently, GMM takes arbitrary non-linear moment conditions and calculates the estimates either for a given weighting matrix or iteratively by alternating between estimating the optimal weighting matrix and estimating the parameters. Implementing models with different moment conditions is done by subclassing GMM. In the minimal implementation only the moment conditions, `momcond` have to be defined.
Module Reference
----------------
| | |
| --- | --- |
| [`GMM`](generated/statsmodels.sandbox.regression.gmm.gmm#statsmodels.sandbox.regression.gmm.GMM "statsmodels.sandbox.regression.gmm.GMM")(endog, exog, instrument[, k\_moms, β¦]) | Class for estimation by Generalized Method of Moments |
| [`GMMResults`](generated/statsmodels.sandbox.regression.gmm.gmmresults#statsmodels.sandbox.regression.gmm.GMMResults "statsmodels.sandbox.regression.gmm.GMMResults")(\*args, \*\*kwds) | just a storage class right now |
| [`IV2SLS`](generated/statsmodels.sandbox.regression.gmm.iv2sls#statsmodels.sandbox.regression.gmm.IV2SLS "statsmodels.sandbox.regression.gmm.IV2SLS")(endog, exog[, instrument]) | Instrumental variables estimation using Two-Stage Least-Squares (2SLS) |
| [`IVGMM`](generated/statsmodels.sandbox.regression.gmm.ivgmm#statsmodels.sandbox.regression.gmm.IVGMM "statsmodels.sandbox.regression.gmm.IVGMM")(endog, exog, instrument[, k\_moms, β¦]) | Basic class for instrumental variables estimation using GMM |
| [`IVGMMResults`](generated/statsmodels.sandbox.regression.gmm.ivgmmresults#statsmodels.sandbox.regression.gmm.IVGMMResults "statsmodels.sandbox.regression.gmm.IVGMMResults")(\*args, \*\*kwds) | |
| [`IVRegressionResults`](generated/statsmodels.sandbox.regression.gmm.ivregressionresults#statsmodels.sandbox.regression.gmm.IVRegressionResults "statsmodels.sandbox.regression.gmm.IVRegressionResults")(model, params[, β¦]) | Results class for for an OLS model. |
| [`LinearIVGMM`](generated/statsmodels.sandbox.regression.gmm.linearivgmm#statsmodels.sandbox.regression.gmm.LinearIVGMM "statsmodels.sandbox.regression.gmm.LinearIVGMM")(endog, exog, instrument[, β¦]) | class for linear instrumental variables models estimated with GMM |
| [`NonlinearIVGMM`](generated/statsmodels.sandbox.regression.gmm.nonlinearivgmm#statsmodels.sandbox.regression.gmm.NonlinearIVGMM "statsmodels.sandbox.regression.gmm.NonlinearIVGMM")(endog, exog, instrument, β¦) | Class for non-linear instrumental variables estimation wusing GMM |
statsmodels endog, exog, whatβs that? endog, exog, whatβs that?
=========================
Statsmodels is using `endog` and `exog` as names for the data, the observed variables that are used in an estimation problem. Other names that are often used in different statistical packages or text books are, for example,
| endog | exog |
| --- | --- |
| y | x |
| y variable | x variable |
| left hand side (LHS) | right hand side (RHS) |
| dependent variable | independent variable |
| regressand | regressors |
| outcome | design |
| response variable | explanatory variable |
The usage is quite often domain and model specific; however, we have chosen to use `endog` and `exog` almost exclusively. A mnenomic hint to keep the two terms apart is that exogenous has an βxβ, as in x-variable, in itβs name.
`x` and `y` are one letter names that are sometimes used for temporary variables and are not informative in itself. To avoid one letter names we decided to use descriptive names and settled on `endog` and `exog`. Since this has been criticized, this might change in future.
Background
----------
Some informal definitions of the terms are
`endogenous`: caused by factors within the system
`exogenous`: caused by factors outside the system
*Endogenous variables designates variables in an economic/econometric model that are explained, or predicted, by that model.* <http://stats.oecd.org/glossary/detail.asp?ID=794>
*Exogenous variables designates variables that appear in an economic/econometric model, but are not explained by that model (i.e. they are taken as given by the model).* <http://stats.oecd.org/glossary/detail.asp?ID=890>
In econometrics and statistics the terms are defined more formally, and different definitions of exogeneity (weak, strong, strict) are used depending on the model. The usage in statsmodels as variable names cannot always be interpreted in a formal sense, but tries to follow the same principle.
In the simplest form, a model relates an observed variable, y, to another set of variables, x, in some linear or nonlinear form
```
y = f(x, beta) + noise
y = x * beta + noise
```
However, to have a statistical model we need additional assumptions on the properties of the explanatory variables, x, and the noise. One standard assumption for many basic models is that x is not correlated with the noise. In a more general definition, x being exogenous means that we do not have to consider how the explanatory variables in x were generated, whether by design or by random draws from some underlying distribution, when we want to estimate the effect or impact that x has on y, or test a hypothesis about this effect.
In other words, y is *endogenous* to our model, x is *exogenous* to our model for the estimation.
As an example, suppose you run an experiment and for the second session some subjects are not available anymore. Is the drop-out relevant for the conclusions you draw for the experiment? In other words, can we treat the drop-out decision as exogenous for our problem.
It is up to the user to know (or to consult a text book to find out) what the underlying statistical assumptions for the models are. As an example, `exog` in `OLS` can have lagged dependent variables if the error or noise term is independently distributed over time (or uncorrelated over time). However, if the error terms are autocorrelated, then OLS does not have good statistical properties (is inconsistent) and the correct model will be ARMAX. `statsmodels` has functions for regression diagnostics to test whether some of the assumptions are justified or not.
statsmodels Nonparametric Methods nonparametric Nonparametric Methods nonparametric
===================================
This section collects various methods in nonparametric statistics. This includes kernel density estimation for univariate and multivariate data, kernel regression and locally weighted scatterplot smoothing (lowess).
sandbox.nonparametric contains additional functions that are work in progress or donβt have unit tests yet. We are planning to include here nonparametric density estimators, especially based on kernel or orthogonal polynomials, smoothers, and tools for nonparametric models and methods in other parts of statsmodels.
Kernel density estimation
-------------------------
The kernel density estimation (KDE) functionality is split between univariate and multivariate estimation, which are implemented in quite different ways.
Univariate estimation (as provided by `KDEUnivariate`) uses FFT transforms, which makes it quite fast. Therefore it should be preferred for *continuous, univariate* data if speed is important. It supports using different kernels; bandwidth estimation is done only by a rule of thumb (Scott or Silverman).
Multivariate estimation (as provided by `KDEMultivariate`) uses product kernels. It supports least squares and maximum likelihood cross-validation for bandwidth estimation, as well as estimating mixed continuous, ordered and unordered data. The default kernels (Gaussian, Wang-Ryzin and Aitchison-Aitken) cannot be altered at the moment however. Direct estimation of the conditional density (\(P(X | Y) = P(X, Y) / P(Y)\)) is supported by `KDEMultivariateConditional`.
`KDEMultivariate` can do univariate estimation as well, but is up to two orders of magnitude slower than `KDEUnivariate`.
Kernel regression
-----------------
Kernel regression (as provided by `KernelReg`) is based on the same product kernel approach as `KDEMultivariate`, and therefore has the same set of features (mixed data, cross-validated bandwidth estimation, kernels) as described above for `KDEMultivariate`. Censored regression is provided by `KernelCensoredReg`.
Note that code for semi-parametric partial linear models and single index models, based on `KernelReg`, can be found in the sandbox.
References
----------
* B.W. Silverman, βDensity Estimation for Statistics and Data Analysisβ
* J.S. Racine, βNonparametric Econometrics: A Primer,β Foundation and Trends in Econometrics, Vol. 3, No. 1, pp. 1-88, 2008.
* Q. Li and J.S. Racine, βNonparametric econometrics: theory and practiceβ, Princeton University Press, 2006.
* Hastie, Tibshirani and Friedman, βThe Elements of Statistical Learning: Data Mining, Inference, and Predictionβ, Springer, 2009.
* Racine, J., Li, Q. βNonparametric Estimation of Distributions with Categorical and Continuous Data.β Working Paper. (2000)
* Racine, J. Li, Q. βKernel Estimation of Multivariate Conditional Distributions Annals of Economics and Finance 5, 211-235 (2004)
* Liu, R., Yang, L. βKernel estimation of multivariate cumulative distribution function.β Journal of Nonparametric Statistics (2008)
* Li, R., Ju, G. βNonparametric Estimation of Multivariate CDF with Categorical and Continuous Data.β Working Paper
* Li, Q., Racine, J. βCross-validated local linear nonparametric regressionβ Statistica Sinica 14(2004), pp. 485-512
* Racine, J.: βConsistent Significance Testing for Nonparametric Regressionβ Journal of Business & Economics Statistics
* Racine, J., Hart, J., Li, Q., βTesting the Significance of Categorical Predictor Variables in Nonparametric Regression Modelsβ, 2006, Econometric Reviews 25, 523-544
Module Reference
----------------
The public functions and classes are
| | |
| --- | --- |
| [`smoothers_lowess.lowess`](generated/statsmodels.nonparametric.smoothers_lowess.lowess#statsmodels.nonparametric.smoothers_lowess.lowess "statsmodels.nonparametric.smoothers_lowess.lowess")(endog, exog[, frac, β¦]) | LOWESS (Locally Weighted Scatterplot Smoothing) |
| [`kde.KDEUnivariate`](generated/statsmodels.nonparametric.kde.kdeunivariate#statsmodels.nonparametric.kde.KDEUnivariate "statsmodels.nonparametric.kde.KDEUnivariate")(endog) | Univariate Kernel Density Estimator. |
| [`kernel_density.KDEMultivariate`](generated/statsmodels.nonparametric.kernel_density.kdemultivariate#statsmodels.nonparametric.kernel_density.KDEMultivariate "statsmodels.nonparametric.kernel_density.KDEMultivariate")(data, var\_type) | Multivariate kernel density estimator. |
| [`kernel_density.KDEMultivariateConditional`](generated/statsmodels.nonparametric.kernel_density.kdemultivariateconditional#statsmodels.nonparametric.kernel_density.KDEMultivariateConditional "statsmodels.nonparametric.kernel_density.KDEMultivariateConditional")(β¦) | Conditional multivariate kernel density estimator. |
| [`kernel_density.EstimatorSettings`](generated/statsmodels.nonparametric.kernel_density.estimatorsettings#statsmodels.nonparametric.kernel_density.EstimatorSettings "statsmodels.nonparametric.kernel_density.EstimatorSettings")([β¦]) | Object to specify settings for density estimation or regression. |
| [`kernel_regression.KernelReg`](generated/statsmodels.nonparametric.kernel_regression.kernelreg#statsmodels.nonparametric.kernel_regression.KernelReg "statsmodels.nonparametric.kernel_regression.KernelReg")(endog, exog, β¦) | Nonparametric kernel regression class. |
| [`kernel_regression.KernelCensoredReg`](generated/statsmodels.nonparametric.kernel_regression.kernelcensoredreg#statsmodels.nonparametric.kernel_regression.KernelCensoredReg "statsmodels.nonparametric.kernel_regression.KernelCensoredReg")(endog, β¦) | Nonparametric censored regression. |
helper functions for kernel bandwidths
| | |
| --- | --- |
| [`bandwidths.bw_scott`](generated/statsmodels.nonparametric.bandwidths.bw_scott#statsmodels.nonparametric.bandwidths.bw_scott "statsmodels.nonparametric.bandwidths.bw_scott")(x[, kernel]) | Scottβs Rule of Thumb |
| [`bandwidths.bw_silverman`](generated/statsmodels.nonparametric.bandwidths.bw_silverman#statsmodels.nonparametric.bandwidths.bw_silverman "statsmodels.nonparametric.bandwidths.bw_silverman")(x[, kernel]) | Silvermanβs Rule of Thumb |
| [`bandwidths.select_bandwidth`](generated/statsmodels.nonparametric.bandwidths.select_bandwidth#statsmodels.nonparametric.bandwidths.select_bandwidth "statsmodels.nonparametric.bandwidths.select_bandwidth")(x, bw, kernel) | Selects bandwidth for a selection rule bw |
There are some examples for nonlinear functions in `statsmodels.nonparametric.dgp_examples`
The sandbox.nonparametric contains additional insufficiently tested classes for testing functional form and for semi-linear and single index models.
statsmodels Distributions Distributions
=============
This section collects various additional functions and methods for statistical distributions.
Empirical Distributions
-----------------------
| | |
| --- | --- |
| [`ECDF`](generated/statsmodels.distributions.empirical_distribution.ecdf#statsmodels.distributions.empirical_distribution.ECDF "statsmodels.distributions.empirical_distribution.ECDF")(x[, side]) | Return the Empirical CDF of an array as a step function. |
| [`StepFunction`](generated/statsmodels.distributions.empirical_distribution.stepfunction#statsmodels.distributions.empirical_distribution.StepFunction "statsmodels.distributions.empirical_distribution.StepFunction")(x, y[, ival, sorted, side]) | A basic step function. |
| [`monotone_fn_inverter`](generated/statsmodels.distributions.empirical_distribution.monotone_fn_inverter#statsmodels.distributions.empirical_distribution.monotone_fn_inverter "statsmodels.distributions.empirical_distribution.monotone_fn_inverter")(fn, x[, vectorized]) | Given a monotone function fn (no checking is done to verify monotonicity) and a set of x values, return an linearly interpolated approximation to its inverse from its values on x. |
Distribution Extras
-------------------
*Skew Distributions*
| | |
| --- | --- |
| [`SkewNorm_gen`](generated/statsmodels.sandbox.distributions.extras.skewnorm_gen#statsmodels.sandbox.distributions.extras.SkewNorm_gen "statsmodels.sandbox.distributions.extras.SkewNorm_gen")() | univariate Skew-Normal distribution of Azzalini |
| [`SkewNorm2_gen`](generated/statsmodels.sandbox.distributions.extras.skewnorm2_gen#statsmodels.sandbox.distributions.extras.SkewNorm2_gen "statsmodels.sandbox.distributions.extras.SkewNorm2_gen")([momtype, a, b, xtol, β¦]) | univariate Skew-Normal distribution of Azzalini |
| [`ACSkewT_gen`](generated/statsmodels.sandbox.distributions.extras.acskewt_gen#statsmodels.sandbox.distributions.extras.ACSkewT_gen "statsmodels.sandbox.distributions.extras.ACSkewT_gen")() | univariate Skew-T distribution of Azzalini |
| [`skewnorm2`](generated/statsmodels.sandbox.distributions.extras.skewnorm2#statsmodels.sandbox.distributions.extras.skewnorm2 "statsmodels.sandbox.distributions.extras.skewnorm2") | univariate Skew-Normal distribution of Azzalini |
*Distributions based on Gram-Charlier expansion*
| | |
| --- | --- |
| [`pdf_moments_st`](generated/statsmodels.sandbox.distributions.extras.pdf_moments_st#statsmodels.sandbox.distributions.extras.pdf_moments_st "statsmodels.sandbox.distributions.extras.pdf_moments_st")(cnt) | Return the Gaussian expanded pdf function given the list of central moments (first one is mean). |
| [`pdf_mvsk`](generated/statsmodels.sandbox.distributions.extras.pdf_mvsk#statsmodels.sandbox.distributions.extras.pdf_mvsk "statsmodels.sandbox.distributions.extras.pdf_mvsk")(mvsk) | Return the Gaussian expanded pdf function given the list of 1st, 2nd moment and skew and Fisher (excess) kurtosis. |
| [`pdf_moments`](generated/statsmodels.sandbox.distributions.extras.pdf_moments#statsmodels.sandbox.distributions.extras.pdf_moments "statsmodels.sandbox.distributions.extras.pdf_moments")(cnt) | Return the Gaussian expanded pdf function given the list of central moments (first one is mean). |
| [`NormExpan_gen`](generated/statsmodels.sandbox.distributions.extras.normexpan_gen#statsmodels.sandbox.distributions.extras.NormExpan_gen "statsmodels.sandbox.distributions.extras.NormExpan_gen")(args, \*\*kwds) | Gram-Charlier Expansion of Normal distribution |
*cdf of multivariate normal* wrapper for scipy.stats
| | |
| --- | --- |
| [`mvstdnormcdf`](generated/statsmodels.sandbox.distributions.extras.mvstdnormcdf#statsmodels.sandbox.distributions.extras.mvstdnormcdf "statsmodels.sandbox.distributions.extras.mvstdnormcdf")(lower, upper, corrcoef, \*\*kwds) | standardized multivariate normal cumulative distribution function |
| [`mvnormcdf`](generated/statsmodels.sandbox.distributions.extras.mvnormcdf#statsmodels.sandbox.distributions.extras.mvnormcdf "statsmodels.sandbox.distributions.extras.mvnormcdf")(upper, mu, cov[, lower]) | multivariate normal cumulative distribution function |
Univariate Distributions by non-linear Transformations
------------------------------------------------------
Univariate distributions can be generated from a non-linear transformation of an existing univariate distribution. `Transf_gen` is a class that can generate a new distribution from a monotonic transformation, `TransfTwo_gen` can use hump-shaped or u-shaped transformation, such as abs or square. The remaining objects are special cases.
| | |
| --- | --- |
| [`TransfTwo_gen`](generated/statsmodels.sandbox.distributions.transformed.transftwo_gen#statsmodels.sandbox.distributions.transformed.TransfTwo_gen "statsmodels.sandbox.distributions.transformed.TransfTwo_gen")(kls, func, funcinvplus, β¦) | Distribution based on a non-monotonic (u- or hump-shaped transformation) |
| [`Transf_gen`](generated/statsmodels.sandbox.distributions.transformed.transf_gen#statsmodels.sandbox.distributions.transformed.Transf_gen "statsmodels.sandbox.distributions.transformed.Transf_gen")(kls, func, funcinv, \*args, \*\*kwargs) | a class for non-linear monotonic transformation of a continuous random variable |
| [`ExpTransf_gen`](generated/statsmodels.sandbox.distributions.transformed.exptransf_gen#statsmodels.sandbox.distributions.transformed.ExpTransf_gen "statsmodels.sandbox.distributions.transformed.ExpTransf_gen")(kls, \*args, \*\*kwargs) | Distribution based on log/exp transformation |
| [`LogTransf_gen`](generated/statsmodels.sandbox.distributions.transformed.logtransf_gen#statsmodels.sandbox.distributions.transformed.LogTransf_gen "statsmodels.sandbox.distributions.transformed.LogTransf_gen")(kls, \*args, \*\*kwargs) | Distribution based on log/exp transformation |
| [`SquareFunc`](generated/statsmodels.sandbox.distributions.transformed.squarefunc#statsmodels.sandbox.distributions.transformed.SquareFunc "statsmodels.sandbox.distributions.transformed.SquareFunc") | class to hold quadratic function with inverse function and derivative |
| [`absnormalg`](generated/statsmodels.sandbox.distributions.transformed.absnormalg#statsmodels.sandbox.distributions.transformed.absnormalg "statsmodels.sandbox.distributions.transformed.absnormalg") | Distribution based on a non-monotonic (u- or hump-shaped transformation) |
| [`invdnormalg`](generated/statsmodels.sandbox.distributions.transformed.invdnormalg#statsmodels.sandbox.distributions.transformed.invdnormalg "statsmodels.sandbox.distributions.transformed.invdnormalg") | a class for non-linear monotonic transformation of a continuous random variable |
| [`loggammaexpg`](generated/statsmodels.sandbox.distributions.transformed.loggammaexpg#statsmodels.sandbox.distributions.transformed.loggammaexpg "statsmodels.sandbox.distributions.transformed.loggammaexpg") | univariate distribution of a non-linear monotonic transformation of a random variable |
| [`lognormalg`](generated/statsmodels.sandbox.distributions.transformed.lognormalg#statsmodels.sandbox.distributions.transformed.lognormalg "statsmodels.sandbox.distributions.transformed.lognormalg") | a class for non-linear monotonic transformation of a continuous random variable |
| [`negsquarenormalg`](generated/statsmodels.sandbox.distributions.transformed.negsquarenormalg#statsmodels.sandbox.distributions.transformed.negsquarenormalg "statsmodels.sandbox.distributions.transformed.negsquarenormalg") | Distribution based on a non-monotonic (u- or hump-shaped transformation) |
| [`squarenormalg`](generated/statsmodels.sandbox.distributions.transformed.squarenormalg#statsmodels.sandbox.distributions.transformed.squarenormalg "statsmodels.sandbox.distributions.transformed.squarenormalg") | Distribution based on a non-monotonic (u- or hump-shaped transformation) |
| [`squaretg`](generated/statsmodels.sandbox.distributions.transformed.squaretg#statsmodels.sandbox.distributions.transformed.squaretg "statsmodels.sandbox.distributions.transformed.squaretg") | Distribution based on a non-monotonic (u- or hump-shaped transformation) |
| programming_docs |
statsmodels Generalized Linear Mixed Effects Models Generalized Linear Mixed Effects Models
=======================================
Generalized Linear Mixed Effects (GLIMMIX) models are generalized linear models with random effects in the linear predictors. Statsmodels currently supports estimation of binomial and Poisson GLIMMIX models using two Bayesian methods: the Laplace approximation to the posterior, and a variational Bayes approximation to the posterior. Both methods provide point estimates (posterior means) and assessments of uncertainty (posterior standard deviation).
The current implementation only supports independent random effects.
Technical Documentation
-----------------------
Unlike Statsmodels mixed linear models, the GLIMMIX implementation is not group-based. Groups are created by interacting all random effects with a categorical variable. Note that this creates large, sparse random effects design matrices `exog_vc`. Internally, `exog_vc` is converted to a scipy sparse matrix. When passing the arguments directly to the class initializer, a sparse matrix may be passed. When using formulas, a dense matrix is created then converted to sparse. For very large problems, it may not be feasible to use formulas due to the size of this dense intermediate matrix.
### References
Blei, Kucukelbir, McAuliffe (2017). Variational Inference: A review for Statisticians <https://arxiv.org/pdf/1601.00670.pdf>
Module Reference
----------------
The model classes are:
| | |
| --- | --- |
| [`BinomialBayesMixedGLM`](generated/statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM")(endog, exog, exog\_vc, β¦) | Fit a generalized linear mixed model using Bayesian methods. |
| [`PoissonBayesMixedGLM`](generated/statsmodels.genmod.bayes_mixed_glm.poissonbayesmixedglm#statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM "statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM")(endog, exog, exog\_vc, ident) | Fit a generalized linear mixed model using Bayesian methods. |
The result class is:
| | |
| --- | --- |
| [`BayesMixedGLMResults`](generated/statsmodels.genmod.bayes_mixed_glm.bayesmixedglmresults#statsmodels.genmod.bayes_mixed_glm.BayesMixedGLMResults "statsmodels.genmod.bayes_mixed_glm.BayesMixedGLMResults")(model, params, cov\_params) | |
statsmodels Regression Diagnostics and Specification Tests Regression Diagnostics and Specification Tests
==============================================
Introduction
------------
In many cases of statistical analysis, we are not sure whether our statistical model is correctly specified. For example when using ols, then linearity and homoscedasticity are assumed, some test statistics additionally assume that the errors are normally distributed or that we have a large sample. Since our results depend on these statistical assumptions, the results are only correct of our assumptions hold (at least approximately).
One solution to the problem of uncertainty about the correct specification is to use robust methods, for example robust regression or robust covariance (sandwich) estimators. The second approach is to test whether our sample is consistent with these assumptions.
The following briefly summarizes specification and diagnostics tests for linear regression.
Heteroscedasticity Tests
------------------------
For these test the null hypothesis is that all observations have the same error variance, i.e. errors are homoscedastic. The tests differ in which kind of heteroscedasticity is considered as alternative hypothesis. They also vary in the power of the test for different types of heteroscedasticity.
[`het_breuschpagan`](generated/statsmodels.stats.diagnostic.het_breuschpagan#statsmodels.stats.diagnostic.het_breuschpagan "statsmodels.stats.diagnostic.het_breuschpagan")
Lagrange Multiplier Heteroscedasticity Test by Breusch-Pagan
[`het_white`](generated/statsmodels.stats.diagnostic.het_white#statsmodels.stats.diagnostic.het_white "statsmodels.stats.diagnostic.het_white")
Lagrange Multiplier Heteroscedasticity Test by White
[`het_goldfeldquandt`](generated/statsmodels.stats.diagnostic.het_goldfeldquandt#statsmodels.stats.diagnostic.het_goldfeldquandt "statsmodels.stats.diagnostic.het_goldfeldquandt")
test whether variance is the same in 2 subsamples Autocorrelation Tests
---------------------
This group of test whether the regression residuals are not autocorrelated. They assume that observations are ordered by time.
`durbin_watson`
* Durbin-Watson test for no autocorrelation of residuals
* printed with summary()
[`acorr_ljungbox`](generated/statsmodels.stats.diagnostic.acorr_ljungbox#statsmodels.stats.diagnostic.acorr_ljungbox "statsmodels.stats.diagnostic.acorr_ljungbox")
* Ljung-Box test for no autocorrelation of residuals
* also returns Box-Pierce statistic
[`acorr_breusch_godfrey`](generated/statsmodels.stats.diagnostic.acorr_breusch_godfrey#statsmodels.stats.diagnostic.acorr_breusch_godfrey "statsmodels.stats.diagnostic.acorr_breusch_godfrey")
* Breusch-Pagan test for no autocorrelation of residuals
missing
* ?
Non-Linearity Tests
-------------------
[`linear_harvey_collier`](generated/statsmodels.stats.diagnostic.linear_harvey_collier#statsmodels.stats.diagnostic.linear_harvey_collier "statsmodels.stats.diagnostic.linear_harvey_collier")
* Multiplier test for Null hypothesis that linear specification is correct
`acorr_linear_rainbow`
* Multiplier test for Null hypothesis that linear specification is correct.
`acorr_linear_lm`
* Lagrange Multiplier test for Null hypothesis that linear specification is correct. This tests against specific functional alternatives.
Tests for Structural Change, Parameter Stability
------------------------------------------------
Test whether all or some regression coefficient are constant over the entire data sample.
### Known Change Point
OneWayLS :
* flexible ols wrapper for testing identical regression coefficients across predefined subsamples (eg. groups)
missing
* predictive test: Greene, number of observations in subsample is smaller than number of regressors
### Unknown Change Point
[`breaks_cusumolsresid`](generated/statsmodels.stats.diagnostic.breaks_cusumolsresid#statsmodels.stats.diagnostic.breaks_cusumolsresid "statsmodels.stats.diagnostic.breaks_cusumolsresid")
* cusum test for parameter stability based on ols residuals
[`breaks_hansen`](generated/statsmodels.stats.diagnostic.breaks_hansen#statsmodels.stats.diagnostic.breaks_hansen "statsmodels.stats.diagnostic.breaks_hansen")
* test for model stability, breaks in parameters for ols, Hansen 1992
[`recursive_olsresiduals`](generated/statsmodels.stats.diagnostic.recursive_olsresiduals#statsmodels.stats.diagnostic.recursive_olsresiduals "statsmodels.stats.diagnostic.recursive_olsresiduals")
Calculate recursive ols with residuals and cusum test statistic. This is currently mainly helper function for recursive residual based tests. However, since it uses recursive updating and doesnβt estimate separate problems it should be also quite efficient as expanding OLS function. missing
* supLM, expLM, aveLM (Andrews, Andrews/Ploberger)
* R-structchange also has musum (moving cumulative sum tests)
* test on recursive parameter estimates, which are there?
Mutlicollinearity Tests
-----------------------
conditionnum (statsmodels.stattools)
* β needs test vs Stata β
* cf Grene (3rd ed.) pp 57-8
numpy.linalg.cond
* (for more general condition numbers, but no behind the scenes help for design preparation)
Variance Inflation Factors This is currently together with influence and outlier measures (with some links to other tests here: <http://www.stata.com/help.cgi?vif>) Normality and Distribution Tests
--------------------------------
`jarque_bera`
* printed with summary()
* test for normal distribution of residuals
Normality tests in scipy stats need to find list again
`omni_normtest`
* test for normal distribution of residuals
* printed with summary()
[`normal_ad`](generated/statsmodels.stats.diagnostic.normal_ad#statsmodels.stats.diagnostic.normal_ad "statsmodels.stats.diagnostic.normal_ad")
* Anderson Darling test for normality with estimated mean and variance
`kstest_normal` [`lilliefors`](generated/statsmodels.stats.diagnostic.lilliefors#statsmodels.stats.diagnostic.lilliefors "statsmodels.stats.diagnostic.lilliefors")
Lilliefors test for normality, this is a Kolmogorov-Smirnov tes with for normality with estimated mean and variance. lilliefors is an alias for kstest\_normal qqplot, scipy.stats.probplot
other goodness-of-fit tests for distributions in scipy.stats and enhancements
* kolmogorov-smirnov
* anderson : Anderson-Darling
* likelihood-ratio, β¦
* chisquare tests, powerdiscrepancy : needs wrapping (for binning)
Outlier and Influence Diagnostic Measures
-----------------------------------------
These measures try to identify observations that are outliers, with large residual, or observations that have a large influence on the regression estimates. Robust Regression, RLM, can be used to both estimate in an outlier robust way as well as identify outlier. The advantage of RLM that the estimation results are not strongly influenced even if there are many outliers, while most of the other measures are better in identifying individual outliers and might not be able to identify groups of outliers.
[`RLM`](generated/statsmodels.robust.robust_linear_model.rlm#statsmodels.robust.robust_linear_model.RLM "statsmodels.robust.robust_linear_model.RLM")
example from example\_rlm.py
```
import statsmodels.api as sm
### Example for using Huber's T norm with the default
### median absolute deviation scaling
data = sm.datasets.stackloss.load()
data.exog = sm.add_constant(data.exog)
huber_t = sm.RLM(data.endog, data.exog, M=sm.robust.norms.HuberT())
hub_results = huber_t.fit()
print(hub_results.weights)
```
And the weights give an idea of how much a particular observation is down-weighted according to the scaling asked for.
[`Influence`](generated/statsmodels.stats.outliers_influence.olsinfluence#statsmodels.stats.outliers_influence.OLSInfluence "statsmodels.stats.outliers_influence.OLSInfluence")
Class in stats.outliers\_influence, most standard measures for outliers and influence are available as methods or attributes given a fitted OLS model. This is mainly written for OLS, some but not all measures are also valid for other models. Some of these statistics can be calculated from an OLS results instance, others require that an OLS is estimated for each left out variable.
* resid\_press
* resid\_studentized\_external
* resid\_studentized\_internal
* ess\_press
* hat\_matrix\_diag
* cooks\_distance - Cookβs Distance [Wikipedia](http://en.wikipedia.org/wiki/Cook%27s_distance) (with some other links)
* cov\_ratio
* dfbetas
* dffits
* dffits\_internal
* det\_cov\_params\_not\_obsi
* params\_not\_obsi
* sigma2\_not\_obsi
Unit Root Tests
---------------
[`unitroot_adf`](generated/statsmodels.stats.diagnostic.unitroot_adf#statsmodels.stats.diagnostic.unitroot_adf "statsmodels.stats.diagnostic.unitroot_adf")
* same as adfuller but with different signature
statsmodels Linear Mixed Effects Models Linear Mixed Effects Models
===========================
Linear Mixed Effects models are used for regression analyses involving dependent data. Such data arise when working with longitudinal and other study designs in which multiple observations are made on each subject. Some specific linear mixed effects models are
* *Random intercepts models*, where all responses in a group are additively shifted by a value that is specific to the group.
* *Random slopes models*, where the responses in a group follow a (conditional) mean trajectory that is linear in the observed covariates, with the slopes (and possibly intercepts) varying by group.
* *Variance components models*, where the levels of one or more categorical covariates are associated with draws from distributions. These random terms additively determine the conditional mean of each observation based on its covariate values.
The Statsmodels implementation of LME is primarily group-based, meaning that random effects must be independently-realized for responses in different groups. There are two types of random effects in our implementation of mixed models: (i) random coefficients (possibly vectors) that have an unknown covariance matrix, and (ii) random coefficients that are independent draws from a common univariate distribution. For both (i) and (ii), the random effects influence the conditional mean of a group through their matrix/vector product with a group-specific design matrix.
A simple example of random coefficients, as in (i) above, is:
\[Y\_{ij} = \beta\_0 + \beta\_1X\_{ij} + \gamma\_{0i} + \gamma\_{1i}X\_{ij} + \epsilon\_{ij}\] Here, \(Y\_{ij}\) is the \(j`th measured response for subject :math:`i\), and \(X\_{ij}\) is a covariate for this response. The βfixed effects parametersβ \(\beta\_0\) and \(\beta\_1\) are shared by all subjects, and the errors \(\epsilon\_{ij}\) are independent of everything else, and identically distributed (with mean zero). The βrandom effects parametersβ \(gamma\_{0i}\) and \(gamma\_{1i}\) follow a bivariate distribution with mean zero, described by three parameters: \({\rm var}\gamma\_{0i}\), \({\rm var}\gamma\_{1i}\), and \({\rm cov}(\gamma\_{0i}, \gamma\_{1i})\). There is also a parameter for \({\rm var}(\epsilon\_{ij})\).
A simple example of variance components, as in (ii) above, is:
\[Y\_{ijk} = \beta\_0 + \eta\_{1i} + \eta\_{2j} + \epsilon\_{ijk}\] Here, \(Y\_{ijk}\) is the \(k`th measured response under conditions :math:`i, j\). The only βmean structure parameterβ is \(\beta\_0\). The \(\eta\_{1i}\) are independent and identically distributed with zero mean, and variance \(\tau\_1^2\), and the \(\eta\_{2j}\) are independent and identically distributed with zero mean, and variance \(\tau\_2^2\).
Statsmodels MixedLM handles most non-crossed random effects models, and some crossed models. To include crossed random effects in a model, it is necessary to treat the entire dataset as a single group. The variance components arguments to the model can then be used to define models with various combinations of crossed and non-crossed random effects.
The Statsmodels LME framework currently supports post-estimation inference via Wald tests and confidence intervals on the coefficients, profile likelihood analysis, likelihood ratio testing, and AIC.
Examples
--------
```
In [1]: import statsmodels.api as sm
In [2]: import statsmodels.formula.api as smf
In [3]: data = sm.datasets.get_rdataset("dietox", "geepack").data
In [4]: md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"])
In [5]: mdf = md.fit()
In [6]: print(mdf.summary())
Mixed Linear Model Regression Results
========================================================
Model: MixedLM Dependent Variable: Weight
No. Observations: 861 Method: REML
No. Groups: 72 Scale: 11.3669
Min. group size: 11 Likelihood: -2404.7753
Max. group size: 12 Converged: Yes
Mean group size: 12.0
--------------------------------------------------------
Coef. Std.Err. z P>|z| [0.025 0.975]
--------------------------------------------------------
Intercept 15.724 0.788 19.952 0.000 14.179 17.268
Time 6.943 0.033 207.939 0.000 6.877 7.008
Group Var 40.394 2.149
========================================================
```
Detailed examples can be found here
* [Mixed LM](examples/notebooks/generated/mixed_lm_example)
There are some notebook examples on the Wiki: [Wiki notebooks for MixedLM](https://github.com/statsmodels/statsmodels/wiki/Examples#linear-mixed-models)
Technical Documentation
-----------------------
The data are partitioned into disjoint groups. The probability model for group \(i\) is:
\[Y = X\beta + Z\gamma + Q\_1\eta\_1 + \cdots + Q\_k\eta\_k + \epsilon\] where
* \(n\_i\) is the number of observations in group \(i\)
* \(Y\) is a \(n\_i\) dimensional response vector
* \(X\) is a \(n\_i \* k\_{fe}\) dimensional matrix of fixed effects coefficients
* \(\beta\) is a \(k\_{fe}\)-dimensional vector of fixed effects slopes
* \(Z\) is a \(n\_i \* k\_{re}\) dimensional matrix of random effects coefficients
* \(\gamma\) is a \(k\_{re}\)-dimensional random vector with mean 0 and covariance matrix \(\Psi\); note that each group gets its own independent realization of gamma.
* \(Q\_j\) is a \(n\_i \times q\_j\) dimensional design matrix for the \(j^{th}\) variance component.
* \(\eta\_j\) is a \(q\_j\)-dimensional random vector containing independent and identically distributed values with variance \(\tau\_j^2\).
* \(\epsilon\) is a \(n\_i\) dimensional vector of i.i.d normal errors with mean 0 and variance \(\sigma^2\); the \(\epsilon\) values are independent both within and between groups
\(Y, X, \{Q\_j\}\) and \(Z\) must be entirely observed. \(\beta\), \(\Psi\), and \(\sigma^2\) are estimated using ML or REML estimation, and \(\gamma\), \(\{\eta\_j\}\) and \(\epsilon\) are random so define the probability model.
The marginal mean structure is \(E[Y|X,Z] = X\*\beta\). If only the marginal mean structure is of interest, GEE is a good alternative to mixed models.
Notation:
* \(cov\_{re}\) is the random effects covariance matrix (referred to above as \(\Psi\)) and \(scale\) is the (scalar) error variance. There is also a single estimated variance parameter \(\tau\_j^2\) for each variance component. For a single group, the marginal covariance matrix of endog given exog is \(scale\*I + Z \* cov\_{re} \* Z\), where \(Z\) is the design matrix for the random effects in one group.
### References
The primary reference for the implementation details is:
* MJ Lindstrom, DM Bates (1988). *Newton Raphson and EM algorithms for linear mixed effects models for repeated measures data*. Journal of the American Statistical Association. Volume 83, Issue 404, pages 1014-1022.
See also this more recent document:
* <http://econ.ucsb.edu/~doug/245a/Papers/Mixed%20Effects%20Implement.pdf>
All the likelihood, gradient, and Hessian calculations closely follow Lindstrom and Bates.
The following two documents are written more from the perspective of users:
* <http://lme4.r-forge.r-project.org/lMMwR/lrgprt.pdf>
* <http://lme4.r-forge.r-project.org/slides/2009-07-07-Rennes/3Longitudinal-4.pdf>
Module Reference
----------------
The model class is:
| | |
| --- | --- |
| [`MixedLM`](generated/statsmodels.regression.mixed_linear_model.mixedlm#statsmodels.regression.mixed_linear_model.MixedLM "statsmodels.regression.mixed_linear_model.MixedLM")(endog, exog, groups[, exog\_re, β¦]) | An object specifying a linear mixed effects model. |
The result class is:
| | |
| --- | --- |
| [`MixedLMResults`](generated/statsmodels.regression.mixed_linear_model.mixedlmresults#statsmodels.regression.mixed_linear_model.MixedLMResults "statsmodels.regression.mixed_linear_model.MixedLMResults")(model, params, cov\_params) | Class to contain results of fitting a linear mixed effects model. |
statsmodels Python Module Index Python Module Index
===================
[**s**](#cap-s)
| | | |
| --- | --- | --- |
| | | |
| | **s** | |
| | [`statsmodels`](http://www.statsmodels.org/stable/about.html#module-statsmodels) | *Statistical analysis in Python* |
| | [`statsmodels.base.model`](http://www.statsmodels.org/stable/dev/internal.html#module-statsmodels.base.model) | *Base classes that are inherited by models* |
| | [`statsmodels.discrete.count_model`](discretemod#module-statsmodels.discrete.count_model) | |
| | [`statsmodels.discrete.discrete_model`](discretemod#module-statsmodels.discrete.discrete_model) | *Models for discrete data* |
| | [`statsmodels.distributions.empirical_distribution`](distributions#module-statsmodels.distributions.empirical_distribution) | *Tools for working with empirical distributions* |
| | [`statsmodels.duration`](duration#module-statsmodels.duration) | *Models for durations* |
| | [`statsmodels.duration.hazard_regression`](duration#module-statsmodels.duration.hazard_regression) | *Proportional hazards model for Survival Analysis* |
| | [`statsmodels.duration.survfunc`](duration#module-statsmodels.duration.survfunc) | *Models for Survival Analysis* |
| | [`statsmodels.emplike`](emplike#module-statsmodels.emplike) | *Empirical likelihood tools* |
| | [`statsmodels.genmod.bayes_mixed_glm`](mixed_glm#module-statsmodels.genmod.bayes_mixed_glm) | *Bayes Mixed Generalized Linear Models* |
| | [`statsmodels.genmod.cov_struct`](gee#module-statsmodels.genmod.cov_struct) | *Covariance structures for Generalized Estimating Equations (GEE)* |
| | [`statsmodels.genmod.families.family`](glm#module-statsmodels.genmod.families.family) | |
| | [`statsmodels.genmod.families.links`](glm#module-statsmodels.genmod.families.links) | |
| | [`statsmodels.genmod.generalized_estimating_equations`](gee#module-statsmodels.genmod.generalized_estimating_equations) | *Generalized estimating equations* |
| | [`statsmodels.genmod.generalized_linear_model`](glm#module-statsmodels.genmod.generalized_linear_model) | *Generalized Linear Models (GLM)* |
| | [`statsmodels.graphics`](graphics#module-statsmodels.graphics) | |
| | [`statsmodels.imputation.mice`](imputation#module-statsmodels.imputation.mice) | *Multiple imputation for missing data* |
| | [`statsmodels.iolib`](iolib#module-statsmodels.iolib) | *Tools for reading datasets and producing summary output* |
| | [`statsmodels.miscmodels`](miscmodels#module-statsmodels.miscmodels) | |
| | [`statsmodels.miscmodels.count`](miscmodels#module-statsmodels.miscmodels.count) | |
| | [`statsmodels.miscmodels.tmodel`](miscmodels#module-statsmodels.miscmodels.tmodel) | |
| | [`statsmodels.multivariate`](multivariate#module-statsmodels.multivariate) | *Models for multivariate data* |
| | [`statsmodels.multivariate.pca`](multivariate#module-statsmodels.multivariate.pca) | *Principal Component Analaysis* |
| | [`statsmodels.nonparametric`](nonparametric#module-statsmodels.nonparametric) | *Nonparametric estimation of densities and curves* |
| | [`statsmodels.regression.linear_model`](regression#module-statsmodels.regression.linear_model) | *Least squares linear models* |
| | [`statsmodels.regression.mixed_linear_model`](mixed_linear#module-statsmodels.regression.mixed_linear_model) | *Mixed Linear Models* |
| | [`statsmodels.regression.quantile_regression`](regression#module-statsmodels.regression.quantile_regression) | *Quantile regression* |
| | [`statsmodels.regression.recursive_ls`](regression#module-statsmodels.regression.recursive_ls) | *Recursive least squares using the Kalman Filter* |
| | [`statsmodels.rlm`](rlm_techn1#module-statsmodels.rlm) | *Outlier robust linear models* |
| | [`statsmodels.robust`](rlm#module-statsmodels.robust) | |
| | [`statsmodels.robust.norms`](rlm#module-statsmodels.robust.norms) | |
| | [`statsmodels.robust.robust_linear_model`](rlm#module-statsmodels.robust.robust_linear_model) | |
| | [`statsmodels.robust.scale`](rlm#module-statsmodels.robust.scale) | |
| | [`statsmodels.sandbox`](sandbox#module-statsmodels.sandbox) | *Experimental tools that have not been fully vetted* |
| | [`statsmodels.sandbox.distributions`](distributions#module-statsmodels.sandbox.distributions) | *Probability distributions* |
| | [`statsmodels.sandbox.distributions.extras`](distributions#module-statsmodels.sandbox.distributions.extras) | *Probability distributions and random number generators* |
| | [`statsmodels.sandbox.distributions.transformed`](distributions#module-statsmodels.sandbox.distributions.transformed) | *Experimental probability distributions and random number generators* |
| | [`statsmodels.sandbox.regression`](sandbox#module-statsmodels.sandbox.regression) | *Experimental regression tools* |
| | [`statsmodels.sandbox.regression.anova_nistcertified`](sandbox#module-statsmodels.sandbox.regression.anova_nistcertified) | *Experimental ANOVA estimator* |
| | [`statsmodels.sandbox.regression.gmm`](gmm#module-statsmodels.sandbox.regression.gmm) | *A framework for implementing Generalized Method of Moments (GMM)* |
| | [`statsmodels.sandbox.stats.multicomp`](stats#module-statsmodels.sandbox.stats.multicomp) | *Experimental methods for controlling size while performing multiple comparisons* |
| | [`statsmodels.sandbox.stats.runs`](stats#module-statsmodels.sandbox.stats.runs) | *Experimental statistical methods and tests to analyze runs* |
| | [`statsmodels.sandbox.sysreg`](sandbox#module-statsmodels.sandbox.sysreg) | *Experimental system regression models* |
| | [`statsmodels.sandbox.tools.tools_tsa`](sandbox#module-statsmodels.sandbox.tools.tools_tsa) | *Experimental tools for working with time-series* |
| | [`statsmodels.sandbox.tsa`](sandbox#module-statsmodels.sandbox.tsa) | *Experimental time-series analysis models* |
| | [`statsmodels.stats`](stats#module-statsmodels.stats) | *Statistical methods and tests* |
| | [`statsmodels.stats.anova`](anova#module-statsmodels.stats.anova) | *Analysis of Variance* |
| | [`statsmodels.stats.contingency_tables`](contingency_tables#module-statsmodels.stats.contingency_tables) | *Contingency table analysis* |
| | [`statsmodels.stats.contrast`](http://www.statsmodels.org/stable/dev/internal.html#module-statsmodels.stats.contrast) | *Classes for statistical test* |
| | [`statsmodels.stats.correlation_tools`](stats#module-statsmodels.stats.correlation_tools) | *Procedures for ensuring correlations are positive semi-definite* |
| | [`statsmodels.stats.descriptivestats`](stats#module-statsmodels.stats.descriptivestats) | *Descriptive statistics* |
| | [`statsmodels.stats.diagnostic`](stats#module-statsmodels.stats.diagnostic) | *Statistical methods and tests to diagnose model fit problems* |
| | [`statsmodels.stats.gof`](stats#module-statsmodels.stats.gof) | *Goodness of fit measures and tests* |
| | [`statsmodels.stats.inter_rater`](stats#module-statsmodels.stats.inter_rater) | |
| | [`statsmodels.stats.mediation`](stats#module-statsmodels.stats.mediation) | *Mediation analysis* |
| | [`statsmodels.stats.moment_helpers`](stats#module-statsmodels.stats.moment_helpers) | *Tools for converting moments* |
| | [`statsmodels.stats.multicomp`](stats#module-statsmodels.stats.multicomp) | *Methods for controlling size while performing multiple comparisons* |
| | [`statsmodels.stats.multitest`](stats#module-statsmodels.stats.multitest) | *Multiple testing p-value and FDR adjustments* |
| | [`statsmodels.stats.outliers_influence`](stats#module-statsmodels.stats.outliers_influence) | *Statistical methods and measures for outliers and influence* |
| | [`statsmodels.stats.power`](stats#module-statsmodels.stats.power) | *Power and size calculations for common tests* |
| | [`statsmodels.stats.proportion`](stats#module-statsmodels.stats.proportion) | *Tests for proportions* |
| | [`statsmodels.stats.stattools`](stats#module-statsmodels.stats.stattools) | *Statistical methods and tests that do not fit into other categories* |
| | [`statsmodels.stats.weightstats`](stats#module-statsmodels.stats.weightstats) | *Weighted statistics* |
| | [`statsmodels.tools`](tools#module-statsmodels.tools) | *Tools for variable transformation and common numerical operations* |
| | [`statsmodels.tsa`](tsa#module-statsmodels.tsa) | *Time-series analysis* |
| | [`statsmodels.tsa.statespace`](statespace#module-statsmodels.tsa.statespace) | *Statespace models for time-series analysis* |
| | [`statsmodels.tsa.vector_ar`](vector_ar#module-statsmodels.tsa.vector_ar) | *Vector autoregressions and related tools* |
| | [`statsmodels.tsa.vector_ar.var_model`](vector_ar#module-statsmodels.tsa.vector_ar.var_model) | *Vector autoregressions* |
| programming_docs |
statsmodels Getting started Getting started
===============
This very simple case-study is designed to get you up-and-running quickly with `statsmodels`. Starting from raw data, we will show the steps needed to estimate a statistical model and to draw a diagnostic plot. We will only use functions provided by `statsmodels` or its `pandas` and `patsy` dependencies.
Loading modules and functions
-----------------------------
After [installing statsmodels and its dependencies](install), we load a few modules and functions:
```
In [1]: from __future__ import print_function
In [2]: import statsmodels.api as sm
In [3]: import pandas
In [4]: from patsy import dmatrices
```
[pandas](http://pandas.pydata.org/) builds on `numpy` arrays to provide rich data structures and data analysis tools. The `pandas.DataFrame` function provides labelled arrays of (potentially heterogenous) data, similar to the `R` βdata.frameβ. The `pandas.read_csv` function can be used to convert a comma-separated values file to a `DataFrame` object.
[patsy](https://github.com/pydata/patsy) is a Python library for describing statistical models and building [Design Matrices](https://en.wikipedia.org/wiki/Design_matrix) using `R`-like formulas.
Data
----
We download the [Guerry dataset](http://vincentarelbundock.github.io/Rdatasets/doc/HistData/Guerry.html), a collection of historical data used in support of Andre-Michel Guerryβs 1833 *Essay on the Moral Statistics of France*. The data set is hosted online in comma-separated values format (CSV) by the [Rdatasets](http://vincentarelbundock.github.io/Rdatasets/) repository. We could download the file locally and then load it using `read_csv`, but `pandas` takes care of all of this automatically for us:
```
In [5]: df = sm.datasets.get_rdataset("Guerry", "HistData").data
```
The [Input/Output doc page](iolib) shows how to import from various other formats.
We select the variables of interest and look at the bottom 5 rows:
```
In [6]: vars = ['Department', 'Lottery', 'Literacy', 'Wealth', 'Region']
In [7]: df = df[vars]
In [8]: df[-5:]
Out[8]:
Department Lottery Literacy Wealth Region
81 Vienne 40 25 68 W
82 Haute-Vienne 55 13 67 C
83 Vosges 14 62 82 E
84 Yonne 51 47 30 C
85 Corse 83 49 37 NaN
```
Notice that there is one missing observation in the *Region* column. We eliminate it using a `DataFrame` method provided by `pandas`:
```
In [9]: df = df.dropna()
In [10]: df[-5:]
Out[10]:
Department Lottery Literacy Wealth Region
80 Vendee 68 28 56 W
81 Vienne 40 25 68 W
82 Haute-Vienne 55 13 67 C
83 Vosges 14 62 82 E
84 Yonne 51 47 30 C
```
Substantive motivation and model
--------------------------------
We want to know whether literacy rates in the 86 French departments are associated with per capita wagers on the Royal Lottery in the 1820s. We need to control for the level of wealth in each department, and we also want to include a series of dummy variables on the right-hand side of our regression equation to control for unobserved heterogeneity due to regional effects. The model is estimated using ordinary least squares regression (OLS).
Design matrices (*endog* & *exog*)
----------------------------------
To fit most of the models covered by `statsmodels`, you will need to create two design matrices. The first is a matrix of endogenous variable(s) (i.e. dependent, response, regressand, etc.). The second is a matrix of exogenous variable(s) (i.e. independent, predictor, regressor, etc.). The OLS coefficient estimates are calculated as usual:
\[\hat{\beta} = (X'X)^{-1} X'y\] where \(y\) is an \(N \times 1\) column of data on lottery wagers per capita (*Lottery*). \(X\) is \(N \times 7\) with an intercept, the *Literacy* and *Wealth* variables, and 4 region binary variables.
The `patsy` module provides a convenient function to prepare design matrices using `R`-like formulas. You can find more information [here](http://patsy.readthedocs.io/en/latest/).
We use `patsy`βs `dmatrices` function to create design matrices:
```
In [11]: y, X = dmatrices('Lottery ~ Literacy + Wealth + Region', data=df, return_type='dataframe')
```
The resulting matrices/data frames look like this:
```
In [12]: y[:3]
Out[12]:
Lottery
0 41.0
1 38.0
2 66.0
In [13]: X[:3]
```
statsmodels Generalized Linear Models Generalized Linear Models
=========================
Generalized linear models currently supports estimation using the one-parameter exponential families.
See [Module Reference](#module-reference) for commands and arguments.
Examples
--------
```
# Load modules and data
In [1]: import statsmodels.api as sm
In [2]: data = sm.datasets.scotland.load()
In [3]: data.exog = sm.add_constant(data.exog)
# Instantiate a gamma family model with the default link function.
In [4]: gamma_model = sm.GLM(data.endog, data.exog, family=sm.families.Gamma())
In [5]: gamma_results = gamma_model.fit()
In [6]: print(gamma_results.summary())
Generalized Linear Model Regression Results
==============================================================================
Dep. Variable: y No. Observations: 32
Model: GLM Df Residuals: 24
Model Family: Gamma Df Model: 7
Link Function: inverse_power Scale: 0.0035843
Method: IRLS Log-Likelihood: -83.017
Date: Mon, 14 May 2018 Deviance: 0.087389
Time: 21:48:07 Pearson chi2: 0.0860
No. Iterations: 6 Covariance Type: nonrobust
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
const -0.0178 0.011 -1.548 0.122 -0.040 0.005
x1 4.962e-05 1.62e-05 3.060 0.002 1.78e-05 8.14e-05
x2 0.0020 0.001 3.824 0.000 0.001 0.003
x3 -7.181e-05 2.71e-05 -2.648 0.008 -0.000 -1.87e-05
x4 0.0001 4.06e-05 2.757 0.006 3.23e-05 0.000
x5 -1.468e-07 1.24e-07 -1.187 0.235 -3.89e-07 9.56e-08
x6 -0.0005 0.000 -2.159 0.031 -0.001 -4.78e-05
x7 -2.427e-06 7.46e-07 -3.253 0.001 -3.89e-06 -9.65e-07
==============================================================================
```
Detailed examples can be found here:
* [GLM](examples/notebooks/generated/glm)
* [Formula](examples/notebooks/generated/glm_formula)
Technical Documentation
-----------------------
The statistical model for each observation \(i\) is assumed to be
\(Y\_i \sim F\_{EDM}(\cdot|\theta,\phi,w\_i)\) and \(\mu\_i = E[Y\_i|x\_i] = g^{-1}(x\_i^\prime\beta)\). where \(g\) is the link function and \(F\_{EDM}(\cdot|\theta,\phi,w)\) is a distribution of the family of exponential dispersion models (EDM) with natural parameter \(\theta\), scale parameter \(\phi\) and weight \(w\). Its density is given by
\(f\_{EDM}(y|\theta,\phi,w) = c(y,\phi,w) \exp\left(\frac{y\theta-b(\theta)}{\phi}w\right)\,.\) It follows that \(\mu = b'(\theta)\) and \(Var[Y|x]=\frac{\phi}{w}b''(\theta)\). The inverse of the first equation gives the natural parameter as a function of the expected value \(\theta(\mu)\) such that
\(Var[Y\_i|x\_i] = \frac{\phi}{w\_i} v(\mu\_i)\) with \(v(\mu) = b''(\theta(\mu))\). Therefore it is said that a GLM is determined by link function \(g\) and variance function \(v(\mu)\) alone (and \(x\) of course).
Note that while \(\phi\) is the same for every observation \(y\_i\) and therefore does not influence the estimation of \(\beta\), the weights \(w\_i\) might be different for every \(y\_i\) such that the estimation of \(\beta\) depends on them.
| Distribution | Domain | \(\mu=E[Y|x]\) | \(v(\mu)\) | \(\theta(\mu)\) | \(b(\theta)\) | \(\phi\) |
| --- | --- | --- | --- | --- | --- | --- |
| Binomial \(B(n,p)\) | \(0,1,\ldots,n\) | \(np\) | \(\mu-\frac{\mu^2}{n}\) | \(\log\frac{p}{1-p}\) | \(n\log(1+e^\theta)\) | 1 |
| Poisson \(P(\mu)\) | \(0,1,\ldots,\infty\) | \(\mu\) | \(\mu\) | \(\log(\mu)\) | \(e^\theta\) | 1 |
| Neg. Binom. \(NB(\mu,\alpha)\) | \(0,1,\ldots,\infty\) | \(\mu\) | \(\mu+\alpha\mu^2\) | \(\log(\frac{\alpha\mu}{1+\alpha\mu})\) | \(-\frac{1}{\alpha}\log(1-\alpha e^\theta)\) | 1 |
| Gaussian/Normal \(N(\mu,\sigma^2)\) | \((-\infty,\infty)\) | \(\mu\) | \(1\) | \(\mu\) | \(\frac{1}{2}\theta^2\) | \(\sigma^2\) |
| Gamma \(N(\mu,\nu)\) | \((0,\infty)\) | \(\mu\) | \(\mu^2\) | \(-\frac{1}{\mu}\) | \(-\log(-\theta)\) | \(\frac{1}{\nu}\) |
| Inv. Gauss. \(IG(\mu,\sigma^2)\) | \((0,\infty)\) | \(\mu\) | \(\mu^3\) | \(-\frac{1}{2\mu^2}\) | \(-\sqrt{-2\theta}\) | \(\sigma^2\) |
| Tweedie \(p\geq 1\) | depends on \(p\) | \(\mu\) | \(\mu^p\) | \(\frac{\mu^{1-p}}{1-p}\) | \(\frac{\alpha-1}{\alpha}\left(\frac{\theta}{\alpha-1}\right)^{\alpha}\) | \(\phi\) |
The Tweedie distribution has special cases for \(p=0,1,2\) not listed in the table and uses \(\alpha=\frac{p-2}{p-1}\).
Correspondence of mathematical variables to code:
* \(Y\) and \(y\) are coded as `endog`, the variable one wants to model
* \(x\) is coded as `exog`, the covariates alias explanatory variables
* \(\beta\) is coded as `params`, the parameters one wants to estimate
* \(\mu\) is coded as `mu`, the expectation (conditional on \(x\)) of \(Y\)
* \(g\) is coded as `link` argument to the `class Family`
* \(\phi\) is coded as `scale`, the dispersion parameter of the EDM
* \(w\) is not yet supported (i.e. \(w=1\)), in the future it might be `var_weights`
* \(p\) is coded as `var_power` for the power of the variance function \(v(\mu)\) of the Tweedie distribution, see table
* \(\alpha\) is either
+ Negative Binomial: the ancillary parameter `alpha`, see table
+ Tweedie: an abbreviation for \(\frac{p-2}{p-1}\) of the power \(p\) of the variance function, see table
### References
* Gill, Jeff. 2000. Generalized Linear Models: A Unified Approach. SAGE QASS Series.
* Green, PJ. 1984. βIteratively reweighted least squares for maximum likelihood estimation, and some robust and resistant alternatives.β Journal of the Royal Statistical Society, Series B, 46, 149-192.
* Hardin, J.W. and Hilbe, J.M. 2007. βGeneralized Linear Models and Extensions.β 2nd ed. Stata Press, College Station, TX.
* McCullagh, P. and Nelder, J.A. 1989. βGeneralized Linear Models.β 2nd ed. Chapman & Hall, Boca Rotan.
Module Reference
----------------
### Model Class
| | |
| --- | --- |
| [`GLM`](generated/statsmodels.genmod.generalized_linear_model.glm#statsmodels.genmod.generalized_linear_model.GLM "statsmodels.genmod.generalized_linear_model.GLM")(endog, exog[, family, offset, exposure, β¦]) | Generalized Linear Models class |
### Results Class
| | |
| --- | --- |
| [`GLMResults`](generated/statsmodels.genmod.generalized_linear_model.glmresults#statsmodels.genmod.generalized_linear_model.GLMResults "statsmodels.genmod.generalized_linear_model.GLMResults")(model, params, β¦[, cov\_type, β¦]) | Class to contain GLM results. |
| [`PredictionResults`](generated/statsmodels.genmod.generalized_linear_model.predictionresults#statsmodels.genmod.generalized_linear_model.PredictionResults "statsmodels.genmod.generalized_linear_model.PredictionResults")(predicted\_mean, var\_pred\_mean) | |
### Families
The distribution families currently implemented are
| | |
| --- | --- |
| [`Family`](generated/statsmodels.genmod.families.family.family#statsmodels.genmod.families.family.Family "statsmodels.genmod.families.family.Family")(link, variance) | The parent class for one-parameter exponential families. |
| [`Binomial`](generated/statsmodels.genmod.families.family.binomial#statsmodels.genmod.families.family.Binomial "statsmodels.genmod.families.family.Binomial")([link]) | Binomial exponential family distribution. |
| [`Gamma`](generated/statsmodels.genmod.families.family.gamma#statsmodels.genmod.families.family.Gamma "statsmodels.genmod.families.family.Gamma")([link]) | Gamma exponential family distribution. |
| [`Gaussian`](generated/statsmodels.genmod.families.family.gaussian#statsmodels.genmod.families.family.Gaussian "statsmodels.genmod.families.family.Gaussian")([link]) | Gaussian exponential family distribution. |
| [`InverseGaussian`](generated/statsmodels.genmod.families.family.inversegaussian#statsmodels.genmod.families.family.InverseGaussian "statsmodels.genmod.families.family.InverseGaussian")([link]) | InverseGaussian exponential family. |
| [`NegativeBinomial`](generated/statsmodels.genmod.families.family.negativebinomial#statsmodels.genmod.families.family.NegativeBinomial "statsmodels.genmod.families.family.NegativeBinomial")([link, alpha]) | Negative Binomial exponential family. |
| [`Poisson`](generated/statsmodels.genmod.families.family.poisson#statsmodels.genmod.families.family.Poisson "statsmodels.genmod.families.family.Poisson")([link]) | Poisson exponential family. |
| [`Tweedie`](generated/statsmodels.genmod.families.family.tweedie#statsmodels.genmod.families.family.Tweedie "statsmodels.genmod.families.family.Tweedie")([link, var\_power]) | Tweedie family. |
### Link Functions
The link functions currently implemented are the following. Not all link functions are available for each distribution family. The list of available link functions can be obtained by
```
>>> sm.families.family.<familyname>.links
```
| | |
| --- | --- |
| [`Link`](generated/statsmodels.genmod.families.links.link#statsmodels.genmod.families.links.Link "statsmodels.genmod.families.links.Link") | A generic link function for one-parameter exponential family. |
| [`CDFLink`](generated/statsmodels.genmod.families.links.cdflink#statsmodels.genmod.families.links.CDFLink "statsmodels.genmod.families.links.CDFLink")([dbn]) | The use the CDF of a scipy.stats distribution |
| [`CLogLog`](generated/statsmodels.genmod.families.links.cloglog#statsmodels.genmod.families.links.CLogLog "statsmodels.genmod.families.links.CLogLog") | The complementary log-log transform |
| [`Log`](generated/statsmodels.genmod.families.links.log#statsmodels.genmod.families.links.Log "statsmodels.genmod.families.links.Log") | The log transform |
| [`Logit`](generated/statsmodels.genmod.families.links.logit#statsmodels.genmod.families.links.Logit "statsmodels.genmod.families.links.Logit") | The logit transform |
| [`NegativeBinomial`](generated/statsmodels.genmod.families.links.negativebinomial#statsmodels.genmod.families.links.NegativeBinomial "statsmodels.genmod.families.links.NegativeBinomial")([alpha]) | The negative binomial link function |
| [`Power`](generated/statsmodels.genmod.families.links.power#statsmodels.genmod.families.links.Power "statsmodels.genmod.families.links.Power")([power]) | The power transform |
| [`cauchy`](generated/statsmodels.genmod.families.links.cauchy#statsmodels.genmod.families.links.cauchy "statsmodels.genmod.families.links.cauchy")() | The Cauchy (standard Cauchy CDF) transform |
| `cloglog` | The CLogLog transform link function. |
| [`identity`](generated/statsmodels.genmod.families.links.identity#statsmodels.genmod.families.links.identity "statsmodels.genmod.families.links.identity")() | The identity transform |
| [`inverse_power`](generated/statsmodels.genmod.families.links.inverse_power#statsmodels.genmod.families.links.inverse_power "statsmodels.genmod.families.links.inverse_power")() | The inverse transform |
| [`inverse_squared`](generated/statsmodels.genmod.families.links.inverse_squared#statsmodels.genmod.families.links.inverse_squared "statsmodels.genmod.families.links.inverse_squared")() | The inverse squared transform |
| `log` | The log transform |
| `logit` | |
| [`nbinom`](generated/statsmodels.genmod.families.links.nbinom#statsmodels.genmod.families.links.nbinom "statsmodels.genmod.families.links.nbinom")([alpha]) | The negative binomial link function. |
| [`probit`](generated/statsmodels.genmod.families.links.probit#statsmodels.genmod.families.links.probit "statsmodels.genmod.families.links.probit")([dbn]) | The probit (standard normal CDF) transform |
statsmodels Input-Output iolib Input-Output iolib
==================
`statsmodels` offers some functions for input and output. These include a reader for STATA files, a class for generating tables for printing in several formats and two helper functions for pickling.
Users can also leverage the powerful input/output functions provided by [pandas.io](http://pandas.pydata.org/pandas-docs/stable/io.html#io "(in pandas v0.22.0)"). Among other things, `pandas` (a `statsmodels` dependency) allows reading and writing to Excel, CSV, and HDF5 (PyTables).
Examples
--------
[SimpleTable: Basic example](examples/notebooks/generated/wls#ols-vs-wls) Module Reference
----------------
| | |
| --- | --- |
| [`foreign.StataReader`](generated/statsmodels.iolib.foreign.statareader#statsmodels.iolib.foreign.StataReader "statsmodels.iolib.foreign.StataReader")(fname[, missing\_values, β¦]) | Stata .dta file reader. |
| [`foreign.StataWriter`](generated/statsmodels.iolib.foreign.statawriter#statsmodels.iolib.foreign.StataWriter "statsmodels.iolib.foreign.StataWriter")(fname, data[, β¦]) | A class for writing Stata binary dta files from array-like objects |
| [`foreign.genfromdta`](generated/statsmodels.iolib.foreign.genfromdta#statsmodels.iolib.foreign.genfromdta "statsmodels.iolib.foreign.genfromdta")(fname[, missing\_flt, β¦]) | Returns an ndarray or DataFrame from a Stata .dta file. |
| [`foreign.savetxt`](generated/statsmodels.iolib.foreign.savetxt#statsmodels.iolib.foreign.savetxt "statsmodels.iolib.foreign.savetxt")(fname, X[, names, fmt, β¦]) | Save an array to a text file. |
| [`table.SimpleTable`](generated/statsmodels.iolib.table.simpletable#statsmodels.iolib.table.SimpleTable "statsmodels.iolib.table.SimpleTable")(data[, headers, stubs, β¦]) | Produce a simple ASCII, CSV, HTML, or LaTeX table from a *rectangular* (2d!) array of data, not necessarily numerical. |
| [`table.csv2st`](generated/statsmodels.iolib.table.csv2st#statsmodels.iolib.table.csv2st "statsmodels.iolib.table.csv2st")(csvfile[, headers, stubs, title]) | Return SimpleTable instance, created from the data in `csvfile`, which is in comma separated values format. |
| [`smpickle.save_pickle`](generated/statsmodels.iolib.smpickle.save_pickle#statsmodels.iolib.smpickle.save_pickle "statsmodels.iolib.smpickle.save_pickle")(obj, fname) | Save the object to file via pickling. |
| [`smpickle.load_pickle`](generated/statsmodels.iolib.smpickle.load_pickle#statsmodels.iolib.smpickle.load_pickle "statsmodels.iolib.smpickle.load_pickle")(fname) | Load a previously saved object from file |
The following are classes and functions used to return the summary of estimation results, and mostly intended for internal use. There are currently two versions for creating summaries.
| | |
| --- | --- |
| [`summary.Summary`](generated/statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary")() | class to hold tables for result summary presentation |
| [`summary2.Summary`](generated/statsmodels.iolib.summary2.summary#statsmodels.iolib.summary2.Summary "statsmodels.iolib.summary2.Summary")() | |
statsmodels Generalized Estimating Equations Generalized Estimating Equations
================================
Generalized Estimating Equations estimate generalized linear models for panel, cluster or repeated measures data when the observations are possibly correlated withing a cluster but uncorrelated across clusters. It supports estimation of the same one-parameter exponential families as Generalized Linear models (`GLM`).
See [Module Reference](#module-reference) for commands and arguments.
Examples
--------
The following illustrates a Poisson regression with exchangeable correlation within clusters using data on epilepsy seizures.
```
In [1]: import statsmodels.api as sm
In [2]: import statsmodels.formula.api as smf
In [3]: data = sm.datasets.get_rdataset('epil', package='MASS').data
In [4]: fam = sm.families.Poisson()
In [5]: ind = sm.cov_struct.Exchangeable()
In [6]: mod = smf.gee("y ~ age + trt + base", "subject", data,
...: cov_struct=ind, family=fam)
...:
In [7]: res = mod.fit()
In [8]: print(res.summary())
GEE Regression Results
===================================================================================
Dep. Variable: y No. Observations: 236
Model: GEE No. clusters: 59
Method: Generalized Min. cluster size: 4
Estimating Equations Max. cluster size: 4
Family: Poisson Mean cluster size: 4.0
Dependence structure: Exchangeable Num. iterations: 51
Date: Mon, 14 May 2018 Scale: 1.000
Covariance type: robust Time: 21:46:28
====================================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------------
Intercept 0.5730 0.361 1.589 0.112 -0.134 1.280
trt[T.progabide] -0.1519 0.171 -0.888 0.375 -0.487 0.183
age 0.0223 0.011 1.960 0.050 2.11e-06 0.045
base 0.0226 0.001 18.451 0.000 0.020 0.025
==============================================================================
Skew: 3.7823 Kurtosis: 28.6672
Centered skew: 2.7597 Centered kurtosis: 21.9865
==============================================================================
```
Several notebook examples of the use of GEE can be found on the Wiki: [Wiki notebooks for GEE](https://github.com/statsmodels/statsmodels/wiki/Examples#generalized-estimating-equations-gee)
### References
* KY Liang and S Zeger. βLongitudinal data analysis using generalized linear modelsβ. Biometrika (1986) 73 (1): 13-22.
* S Zeger and KY Liang. βLongitudinal Data Analysis for Discrete and Continuous Outcomesβ. Biometrics Vol. 42, No. 1 (Mar., 1986), pp. 121-130
* A Rotnitzky and NP Jewell (1990). βHypothesis testing of regression parameters in semiparametric generalized linear models for cluster correlated dataβ, Biometrika, 77, 485-497.
* Xu Guo and Wei Pan (2002). βSmall sample performance of the score test in GEEβ. <http://www.sph.umn.edu/faculty1/wp-content/uploads/2012/11/rr2002-013.pdf>
* LA Mancl LA, TA DeRouen (2001). A covariance estimator for GEE with improved small-sample properties. Biometrics. 2001 Mar;57(1):126-34.
Module Reference
----------------
### Model Class
| | |
| --- | --- |
| [`GEE`](generated/statsmodels.genmod.generalized_estimating_equations.gee#statsmodels.genmod.generalized_estimating_equations.GEE "statsmodels.genmod.generalized_estimating_equations.GEE")(endog, exog, groups[, time, family, β¦]) | Estimation of marginal regression models using Generalized Estimating Equations (GEE). |
### Results Classes
| | |
| --- | --- |
| [`GEEResults`](generated/statsmodels.genmod.generalized_estimating_equations.geeresults#statsmodels.genmod.generalized_estimating_equations.GEEResults "statsmodels.genmod.generalized_estimating_equations.GEEResults")(model, params, cov\_params, scale) | This class summarizes the fit of a marginal regression model using GEE. |
| [`GEEMargins`](generated/statsmodels.genmod.generalized_estimating_equations.geemargins#statsmodels.genmod.generalized_estimating_equations.GEEMargins "statsmodels.genmod.generalized_estimating_equations.GEEMargins")(results, args[, kwargs]) | Estimated marginal effects for a regression model fit with GEE. |
### Dependence Structures
The dependence structures currently implemented are
| | |
| --- | --- |
| [`CovStruct`](generated/statsmodels.genmod.cov_struct.covstruct#statsmodels.genmod.cov_struct.CovStruct "statsmodels.genmod.cov_struct.CovStruct")([cov\_nearest\_method]) | A base class for correlation and covariance structures of grouped data. |
| [`Autoregressive`](generated/statsmodels.genmod.cov_struct.autoregressive#statsmodels.genmod.cov_struct.Autoregressive "statsmodels.genmod.cov_struct.Autoregressive")([dist\_func]) | A first-order autoregressive working dependence structure. |
| [`Exchangeable`](generated/statsmodels.genmod.cov_struct.exchangeable#statsmodels.genmod.cov_struct.Exchangeable "statsmodels.genmod.cov_struct.Exchangeable")() | An exchangeable working dependence structure. |
| [`GlobalOddsRatio`](generated/statsmodels.genmod.cov_struct.globaloddsratio#statsmodels.genmod.cov_struct.GlobalOddsRatio "statsmodels.genmod.cov_struct.GlobalOddsRatio")(endog\_type) | Estimate the global odds ratio for a GEE with ordinal or nominal data. |
| [`Independence`](generated/statsmodels.genmod.cov_struct.independence#statsmodels.genmod.cov_struct.Independence "statsmodels.genmod.cov_struct.Independence")([cov\_nearest\_method]) | An independence working dependence structure. |
| [`Nested`](generated/statsmodels.genmod.cov_struct.nested#statsmodels.genmod.cov_struct.Nested "statsmodels.genmod.cov_struct.Nested")([cov\_nearest\_method]) | A nested working dependence structure. |
### Families
The distribution families are the same as for GLM, currently implemented are
| | |
| --- | --- |
| [`Family`](generated/statsmodels.genmod.families.family.family#statsmodels.genmod.families.family.Family "statsmodels.genmod.families.family.Family")(link, variance) | The parent class for one-parameter exponential families. |
| [`Binomial`](generated/statsmodels.genmod.families.family.binomial#statsmodels.genmod.families.family.Binomial "statsmodels.genmod.families.family.Binomial")([link]) | Binomial exponential family distribution. |
| [`Gamma`](generated/statsmodels.genmod.families.family.gamma#statsmodels.genmod.families.family.Gamma "statsmodels.genmod.families.family.Gamma")([link]) | Gamma exponential family distribution. |
| [`Gaussian`](generated/statsmodels.genmod.families.family.gaussian#statsmodels.genmod.families.family.Gaussian "statsmodels.genmod.families.family.Gaussian")([link]) | Gaussian exponential family distribution. |
| [`InverseGaussian`](generated/statsmodels.genmod.families.family.inversegaussian#statsmodels.genmod.families.family.InverseGaussian "statsmodels.genmod.families.family.InverseGaussian")([link]) | InverseGaussian exponential family. |
| [`NegativeBinomial`](generated/statsmodels.genmod.families.family.negativebinomial#statsmodels.genmod.families.family.NegativeBinomial "statsmodels.genmod.families.family.NegativeBinomial")([link, alpha]) | Negative Binomial exponential family. |
| [`Poisson`](generated/statsmodels.genmod.families.family.poisson#statsmodels.genmod.families.family.Poisson "statsmodels.genmod.families.family.Poisson")([link]) | Poisson exponential family. |
### Link Functions
The link functions are the same as for GLM, currently implemented are the following. Not all link functions are available for each distribution family. The list of available link functions can be obtained by
```
>>> sm.families.family.<familyname>.links
```
| | |
| --- | --- |
| [`Link`](generated/statsmodels.genmod.families.links.link#statsmodels.genmod.families.links.Link "statsmodels.genmod.families.links.Link") | A generic link function for one-parameter exponential family. |
| [`CDFLink`](generated/statsmodels.genmod.families.links.cdflink#statsmodels.genmod.families.links.CDFLink "statsmodels.genmod.families.links.CDFLink")([dbn]) | The use the CDF of a scipy.stats distribution |
| [`CLogLog`](generated/statsmodels.genmod.families.links.cloglog#statsmodels.genmod.families.links.CLogLog "statsmodels.genmod.families.links.CLogLog") | The complementary log-log transform |
| [`Log`](generated/statsmodels.genmod.families.links.log#statsmodels.genmod.families.links.Log "statsmodels.genmod.families.links.Log") | The log transform |
| [`Logit`](generated/statsmodels.genmod.families.links.logit#statsmodels.genmod.families.links.Logit "statsmodels.genmod.families.links.Logit") | The logit transform |
| [`NegativeBinomial`](generated/statsmodels.genmod.families.links.negativebinomial#statsmodels.genmod.families.links.NegativeBinomial "statsmodels.genmod.families.links.NegativeBinomial")([alpha]) | The negative binomial link function |
| [`Power`](generated/statsmodels.genmod.families.links.power#statsmodels.genmod.families.links.Power "statsmodels.genmod.families.links.Power")([power]) | The power transform |
| [`cauchy`](generated/statsmodels.genmod.families.links.cauchy#statsmodels.genmod.families.links.cauchy "statsmodels.genmod.families.links.cauchy")() | The Cauchy (standard Cauchy CDF) transform |
| `cloglog` | The CLogLog transform link function. |
| [`identity`](generated/statsmodels.genmod.families.links.identity#statsmodels.genmod.families.links.identity "statsmodels.genmod.families.links.identity")() | The identity transform |
| [`inverse_power`](generated/statsmodels.genmod.families.links.inverse_power#statsmodels.genmod.families.links.inverse_power "statsmodels.genmod.families.links.inverse_power")() | The inverse transform |
| [`inverse_squared`](generated/statsmodels.genmod.families.links.inverse_squared#statsmodels.genmod.families.links.inverse_squared "statsmodels.genmod.families.links.inverse_squared")() | The inverse squared transform |
| `log` | The log transform |
| `logit` | |
| [`nbinom`](generated/statsmodels.genmod.families.links.nbinom#statsmodels.genmod.families.links.nbinom "statsmodels.genmod.families.links.nbinom")([alpha]) | The negative binomial link function. |
| [`probit`](generated/statsmodels.genmod.families.links.probit#statsmodels.genmod.families.links.probit "statsmodels.genmod.families.links.probit")([dbn]) | The probit (standard normal CDF) transform |
| programming_docs |
statsmodels Contingency tables Contingency tables
==================
Statsmodels supports a variety of approaches for analyzing contingency tables, including methods for assessing independence, symmetry, homogeneity, and methods for working with collections of tables from a stratified population.
The methods described here are mainly for two-way tables. Multi-way tables can be analyzed using log-linear models. Statsmodels does not currently have a dedicated API for loglinear modeling, but Poisson regression in `statsmodels.genmod.GLM` can be used for this purpose.
A contingency table is a multi-way table that describes a data set in which each observation belongs to one category for each of several variables. For example, if there are two variables, one with \(r\) levels and one with \(c\) levels, then we have a \(r \times c\) contingency table. The table can be described in terms of the number of observations that fall into a given cell of the table, e.g. \(T\_{ij}\) is the number of observations that have level \(i\) for the first variable and level \(j\) for the second variable. Note that each variable must have a finite number of levels (or categories), which can be either ordered or unordered. In different contexts, the variables defining the axes of a contingency table may be called **categorical variables** or **factor variables**. They may be either **nominal** (if their levels are unordered) or **ordinal** (if their levels are ordered).
The underlying population for a contingency table is described by a **distribution table** \(P\_{i, j}\). The elements of \(P\) are probabilities, and the sum of all elements in \(P\) is 1. Methods for analyzing contingency tables use the data in \(T\) to learn about properties of \(P\).
The `statsmodels.stats.Table` is the most basic class for working with contingency tables. We can create a `Table` object directly from any rectangular array-like object containing the contingency table cell counts:
```
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: import statsmodels.api as sm
In [4]: df = sm.datasets.get_rdataset("Arthritis", "vcd").data
In [5]: tab = pd.crosstab(df['Treatment'], df['Improved'])
In [6]: tab = tab.loc[:, ["None", "Some", "Marked"]]
In [7]: table = sm.stats.Table(tab)
```
Alternatively, we can pass the raw data and let the Table class construct the array of cell counts for us:
```
In [8]: table = sm.stats.Table.from_data(df[["Treatment", "Improved"]])
```
Independence
------------
**Independence** is the property that the row and column factors occur independently. **Association** is the lack of independence. If the joint distribution is independent, it can be written as the outer product of the row and column marginal distributions:
\[\] P\_{ij} = sum\_k P\_{ij} cdot sum\_k P\_{kj} forall i, j
We can obtain the best-fitting independent distribution for our observed data, and then view residuals which identify particular cells that most strongly violate independence:
```
In [9]: print(table.table_orig)
Improved Marked None Some
Treatment
Placebo 7 29 7
Treated 21 13 7
In [10]: print(table.fittedvalues)
```
statsmodels Time Series analysis tsa Time Series analysis tsa
========================
[`statsmodels.tsa`](#module-statsmodels.tsa "statsmodels.tsa: Time-series analysis") contains model classes and functions that are useful for time series analysis. Basic models include univariate autoregressive models (AR), vector autoregressive models (VAR) and univariate autoregressive moving average models (ARMA). Non-linear models include Markov switching dynamic regression and autoregression. It also includes descriptive statistics for time series, for example autocorrelation, partial autocorrelation function and periodogram, as well as the corresponding theoretical properties of ARMA or related processes. It also includes methods to work with autoregressive and moving average lag-polynomials. Additionally, related statistical tests and some useful helper functions are available.
Estimation is either done by exact or conditional Maximum Likelihood or conditional least-squares, either using Kalman Filter or direct filters.
Currently, functions and classes have to be imported from the corresponding module, but the main classes will be made available in the statsmodels.tsa namespace. The module structure is within statsmodels.tsa is
* stattools : empirical properties and tests, acf, pacf, granger-causality, adf unit root test, kpss test, bds test, ljung-box test and others.
* ar\_model : univariate autoregressive process, estimation with conditional and exact maximum likelihood and conditional least-squares
* arima\_model : univariate ARMA process, estimation with conditional and exact maximum likelihood and conditional least-squares
* vector\_ar, var : vector autoregressive process (VAR) estimation models, impulse response analysis, forecast error variance decompositions, and data visualization tools
* kalmanf : estimation classes for ARMA and other models with exact MLE using Kalman Filter
* arma\_process : properties of arma processes with given parameters, this includes tools to convert between ARMA, MA and AR representation as well as acf, pacf, spectral density, impulse response function and similar
* sandbox.tsa.fftarma : similar to arma\_process but working in frequency domain
* tsatools : additional helper functions, to create arrays of lagged variables, construct regressors for trend, detrend and similar.
* filters : helper function for filtering time series
* regime\_switching : Markov switching dynamic regression and autoregression models
Some additional functions that are also useful for time series analysis are in other parts of statsmodels, for example additional statistical tests.
Some related functions are also available in matplotlib, nitime, and scikits.talkbox. Those functions are designed more for the use in signal processing where longer time series are available and work more often in the frequency domain.
Descriptive Statistics and Tests
--------------------------------
| | |
| --- | --- |
| [`stattools.acovf`](generated/statsmodels.tsa.stattools.acovf#statsmodels.tsa.stattools.acovf "statsmodels.tsa.stattools.acovf")(x[, unbiased, demean, fft, β¦]) | Autocovariance for 1D |
| [`stattools.acf`](generated/statsmodels.tsa.stattools.acf#statsmodels.tsa.stattools.acf "statsmodels.tsa.stattools.acf")(x[, unbiased, nlags, qstat, β¦]) | Autocorrelation function for 1d arrays. |
| [`stattools.pacf`](generated/statsmodels.tsa.stattools.pacf#statsmodels.tsa.stattools.pacf "statsmodels.tsa.stattools.pacf")(x[, nlags, method, alpha]) | Partial autocorrelation estimated |
| [`stattools.pacf_yw`](generated/statsmodels.tsa.stattools.pacf_yw#statsmodels.tsa.stattools.pacf_yw "statsmodels.tsa.stattools.pacf_yw")(x[, nlags, method]) | Partial autocorrelation estimated with non-recursive yule\_walker |
| [`stattools.pacf_ols`](generated/statsmodels.tsa.stattools.pacf_ols#statsmodels.tsa.stattools.pacf_ols "statsmodels.tsa.stattools.pacf_ols")(x[, nlags]) | Calculate partial autocorrelations |
| [`stattools.ccovf`](generated/statsmodels.tsa.stattools.ccovf#statsmodels.tsa.stattools.ccovf "statsmodels.tsa.stattools.ccovf")(x, y[, unbiased, demean]) | crosscovariance for 1D |
| [`stattools.ccf`](generated/statsmodels.tsa.stattools.ccf#statsmodels.tsa.stattools.ccf "statsmodels.tsa.stattools.ccf")(x, y[, unbiased]) | cross-correlation function for 1d |
| [`stattools.periodogram`](generated/statsmodels.tsa.stattools.periodogram#statsmodels.tsa.stattools.periodogram "statsmodels.tsa.stattools.periodogram")(X) | Returns the periodogram for the natural frequency of X |
| [`stattools.adfuller`](generated/statsmodels.tsa.stattools.adfuller#statsmodels.tsa.stattools.adfuller "statsmodels.tsa.stattools.adfuller")(x[, maxlag, regression, β¦]) | Augmented Dickey-Fuller unit root test |
| [`stattools.kpss`](generated/statsmodels.tsa.stattools.kpss#statsmodels.tsa.stattools.kpss "statsmodels.tsa.stattools.kpss")(x[, regression, lags, store]) | Kwiatkowski-Phillips-Schmidt-Shin test for stationarity. |
| [`stattools.coint`](generated/statsmodels.tsa.stattools.coint#statsmodels.tsa.stattools.coint "statsmodels.tsa.stattools.coint")(y0, y1[, trend, method, β¦]) | Test for no-cointegration of a univariate equation |
| [`stattools.bds`](generated/statsmodels.tsa.stattools.bds#statsmodels.tsa.stattools.bds "statsmodels.tsa.stattools.bds")(x[, max\_dim, epsilon, distance]) | Calculate the BDS test statistic for independence of a time series |
| [`stattools.q_stat`](generated/statsmodels.tsa.stattools.q_stat#statsmodels.tsa.stattools.q_stat "statsmodels.tsa.stattools.q_stat")(x, nobs[, type]) | Returnβs Ljung-Box Q Statistic |
| [`stattools.grangercausalitytests`](generated/statsmodels.tsa.stattools.grangercausalitytests#statsmodels.tsa.stattools.grangercausalitytests "statsmodels.tsa.stattools.grangercausalitytests")(x, maxlag[, β¦]) | four tests for granger non causality of 2 timeseries |
| [`stattools.levinson_durbin`](generated/statsmodels.tsa.stattools.levinson_durbin#statsmodels.tsa.stattools.levinson_durbin "statsmodels.tsa.stattools.levinson_durbin")(s[, nlags, isacov]) | Levinson-Durbin recursion for autoregressive processes |
| [`stattools.arma_order_select_ic`](generated/statsmodels.tsa.stattools.arma_order_select_ic#statsmodels.tsa.stattools.arma_order_select_ic "statsmodels.tsa.stattools.arma_order_select_ic")(y[, max\_ar, β¦]) | Returns information criteria for many ARMA models |
| [`x13.x13_arima_select_order`](generated/statsmodels.tsa.x13.x13_arima_select_order#statsmodels.tsa.x13.x13_arima_select_order "statsmodels.tsa.x13.x13_arima_select_order")(endog[, β¦]) | Perform automatic seaonal ARIMA order identification using x12/x13 ARIMA. |
| [`x13.x13_arima_analysis`](generated/statsmodels.tsa.x13.x13_arima_analysis#statsmodels.tsa.x13.x13_arima_analysis "statsmodels.tsa.x13.x13_arima_analysis")(endog[, maxorder, β¦]) | Perform x13-arima analysis for monthly or quarterly data. |
Estimation
----------
The following are the main estimation classes, which can be accessed through statsmodels.tsa.api and their result classes
### Univariate Autogressive Processes (AR)
| | |
| --- | --- |
| [`ar_model.AR`](generated/statsmodels.tsa.ar_model.ar#statsmodels.tsa.ar_model.AR "statsmodels.tsa.ar_model.AR")(endog[, dates, freq, missing]) | Autoregressive AR(p) model |
| [`ar_model.ARResults`](generated/statsmodels.tsa.ar_model.arresults#statsmodels.tsa.ar_model.ARResults "statsmodels.tsa.ar_model.ARResults")(model, params[, β¦]) | Class to hold results from fitting an AR model. |
### Autogressive Moving-Average Processes (ARMA) and Kalman Filter
| | |
| --- | --- |
| [`arima_model.ARMA`](generated/statsmodels.tsa.arima_model.arma#statsmodels.tsa.arima_model.ARMA "statsmodels.tsa.arima_model.ARMA")(endog, order[, exog, β¦]) | Autoregressive Moving Average ARMA(p,q) Model |
| [`arima_model.ARMAResults`](generated/statsmodels.tsa.arima_model.armaresults#statsmodels.tsa.arima_model.ARMAResults "statsmodels.tsa.arima_model.ARMAResults")(model, params[, β¦]) | Class to hold results from fitting an ARMA model. |
| [`arima_model.ARIMA`](generated/statsmodels.tsa.arima_model.arima#statsmodels.tsa.arima_model.ARIMA "statsmodels.tsa.arima_model.ARIMA")(endog, order[, exog, β¦]) | Autoregressive Integrated Moving Average ARIMA(p,d,q) Model |
| [`arima_model.ARIMAResults`](generated/statsmodels.tsa.arima_model.arimaresults#statsmodels.tsa.arima_model.ARIMAResults "statsmodels.tsa.arima_model.ARIMAResults")(model, params[, β¦]) | |
| [`kalmanf.kalmanfilter.KalmanFilter`](generated/statsmodels.tsa.kalmanf.kalmanfilter.kalmanfilter#statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter "statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter") | Kalman Filter code intended for use with the ARMA model. |
### Exponential Smoothing
| | |
| --- | --- |
| [`holtwinters.ExponentialSmoothing`](generated/statsmodels.tsa.holtwinters.exponentialsmoothing#statsmodels.tsa.holtwinters.ExponentialSmoothing "statsmodels.tsa.holtwinters.ExponentialSmoothing")(endog[, β¦]) | Holt Winterβs Exponential Smoothing |
| [`holtwinters.SimpleExpSmoothing`](generated/statsmodels.tsa.holtwinters.simpleexpsmoothing#statsmodels.tsa.holtwinters.SimpleExpSmoothing "statsmodels.tsa.holtwinters.SimpleExpSmoothing")(endog) | Simple Exponential Smoothing wrapper(β¦) |
| [`holtwinters.Holt`](generated/statsmodels.tsa.holtwinters.holt#statsmodels.tsa.holtwinters.Holt "statsmodels.tsa.holtwinters.Holt")(endog[, exponential, damped]) | Holtβs Exponential Smoothing wrapper(β¦) |
| [`holtwinters.HoltWintersResults`](generated/statsmodels.tsa.holtwinters.holtwintersresults#statsmodels.tsa.holtwinters.HoltWintersResults "statsmodels.tsa.holtwinters.HoltWintersResults")(model, β¦) | Holt Winterβs Exponential Smoothing Results |
### Vector Autogressive Processes (VAR)
| | |
| --- | --- |
| [`vector_ar.var_model.VAR`](generated/statsmodels.tsa.vector_ar.var_model.var#statsmodels.tsa.vector_ar.var_model.VAR "statsmodels.tsa.vector_ar.var_model.VAR")(endog[, exog, β¦]) | Fit VAR(p) process and do lag order selection |
| [`vector_ar.var_model.VARResults`](generated/statsmodels.tsa.vector_ar.var_model.varresults#statsmodels.tsa.vector_ar.var_model.VARResults "statsmodels.tsa.vector_ar.var_model.VARResults")(endog, β¦[, β¦]) | Estimate VAR(p) process with fixed number of lags |
| [`vector_ar.dynamic.DynamicVAR`](generated/statsmodels.tsa.vector_ar.dynamic.dynamicvar#statsmodels.tsa.vector_ar.dynamic.DynamicVAR "statsmodels.tsa.vector_ar.dynamic.DynamicVAR")(data[, β¦]) | Estimates time-varying vector autoregression (VAR(p)) using equation-by-equation least squares |
See also
tutorial [VAR documentation](vector_ar#var)
Vector Autogressive Processes (VAR)
-----------------------------------
Besides estimation, several process properties and additional results after estimation are available for vector autoregressive processes.
| | |
| --- | --- |
| [`vector_ar.var_model.LagOrderResults`](generated/statsmodels.tsa.vector_ar.var_model.lagorderresults#statsmodels.tsa.vector_ar.var_model.LagOrderResults "statsmodels.tsa.vector_ar.var_model.LagOrderResults")(ics, β¦) | Results class for choosing a modelβs lag order. |
| [`vector_ar.var_model.VAR`](generated/statsmodels.tsa.vector_ar.var_model.var#statsmodels.tsa.vector_ar.var_model.VAR "statsmodels.tsa.vector_ar.var_model.VAR")(endog[, exog, β¦]) | Fit VAR(p) process and do lag order selection |
| [`vector_ar.var_model.VARProcess`](generated/statsmodels.tsa.vector_ar.var_model.varprocess#statsmodels.tsa.vector_ar.var_model.VARProcess "statsmodels.tsa.vector_ar.var_model.VARProcess")(coefs, β¦[, β¦]) | Class represents a known VAR(p) process |
| [`vector_ar.var_model.VARResults`](generated/statsmodels.tsa.vector_ar.var_model.varresults#statsmodels.tsa.vector_ar.var_model.VARResults "statsmodels.tsa.vector_ar.var_model.VARResults")(endog, β¦[, β¦]) | Estimate VAR(p) process with fixed number of lags |
| [`vector_ar.irf.IRAnalysis`](generated/statsmodels.tsa.vector_ar.irf.iranalysis#statsmodels.tsa.vector_ar.irf.IRAnalysis "statsmodels.tsa.vector_ar.irf.IRAnalysis")(model[, P, β¦]) | Impulse response analysis class. |
| [`vector_ar.var_model.FEVD`](generated/statsmodels.tsa.vector_ar.var_model.fevd#statsmodels.tsa.vector_ar.var_model.FEVD "statsmodels.tsa.vector_ar.var_model.FEVD")(model[, P, periods]) | Compute and plot Forecast error variance decomposition and asymptotic standard errors |
| [`vector_ar.hypothesis_test_results.HypothesisTestResults`](generated/statsmodels.tsa.vector_ar.hypothesis_test_results.hypothesistestresults#statsmodels.tsa.vector_ar.hypothesis_test_results.HypothesisTestResults "statsmodels.tsa.vector_ar.hypothesis_test_results.HypothesisTestResults")(β¦) | Results class for hypothesis tests. |
| [`vector_ar.hypothesis_test_results.CausalityTestResults`](generated/statsmodels.tsa.vector_ar.hypothesis_test_results.causalitytestresults#statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults "statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults")(β¦) | Results class for Granger-causality and instantaneous causality. |
| [`vector_ar.hypothesis_test_results.NormalityTestResults`](generated/statsmodels.tsa.vector_ar.hypothesis_test_results.normalitytestresults#statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults "statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults")(β¦) | Results class for the Jarque-Bera-test for nonnormality. |
| [`vector_ar.hypothesis_test_results.WhitenessTestResults`](generated/statsmodels.tsa.vector_ar.hypothesis_test_results.whitenesstestresults#statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults "statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults")(β¦) | Results class for the Portmanteau-test for residual autocorrelation. |
| [`vector_ar.dynamic.DynamicVAR`](generated/statsmodels.tsa.vector_ar.dynamic.dynamicvar#statsmodels.tsa.vector_ar.dynamic.DynamicVAR "statsmodels.tsa.vector_ar.dynamic.DynamicVAR")(data[, β¦]) | Estimates time-varying vector autoregression (VAR(p)) using equation-by-equation least squares |
See also
tutorial [VAR documentation](vector_ar#var)
Vector Error Correction Models (VECM)
-------------------------------------
| | |
| --- | --- |
| [`vector_ar.vecm.select_order`](generated/statsmodels.tsa.vector_ar.vecm.select_order#statsmodels.tsa.vector_ar.vecm.select_order "statsmodels.tsa.vector_ar.vecm.select_order")(data, maxlags[, β¦]) | Compute lag order selections based on each of the available information criteria. |
| [`vector_ar.vecm.select_coint_rank`](generated/statsmodels.tsa.vector_ar.vecm.select_coint_rank#statsmodels.tsa.vector_ar.vecm.select_coint_rank "statsmodels.tsa.vector_ar.vecm.select_coint_rank")(endog, β¦) | Calculate the cointegration rank of a VECM. |
| [`vector_ar.vecm.CointRankResults`](generated/statsmodels.tsa.vector_ar.vecm.cointrankresults#statsmodels.tsa.vector_ar.vecm.CointRankResults "statsmodels.tsa.vector_ar.vecm.CointRankResults")(rank, neqs, β¦) | A class for holding the results from testing the cointegration rank. |
| [`vector_ar.vecm.VECM`](generated/statsmodels.tsa.vector_ar.vecm.vecm#statsmodels.tsa.vector_ar.vecm.VECM "statsmodels.tsa.vector_ar.vecm.VECM")(endog[, exog, β¦]) | Class representing a Vector Error Correction Model (VECM). |
| [`vector_ar.vecm.VECMResults`](generated/statsmodels.tsa.vector_ar.vecm.vecmresults#statsmodels.tsa.vector_ar.vecm.VECMResults "statsmodels.tsa.vector_ar.vecm.VECMResults")(endog, exog, β¦) | Class for holding estimation related results of a vector error correction model (VECM). |
| [`vector_ar.vecm.coint_johansen`](generated/statsmodels.tsa.vector_ar.vecm.coint_johansen#statsmodels.tsa.vector_ar.vecm.coint_johansen "statsmodels.tsa.vector_ar.vecm.coint_johansen")(endog, β¦) | Perform the Johansen cointegration test for determining the cointegration rank of a VECM. |
Regime switching models
-----------------------
| | |
| --- | --- |
| [`regime_switching.markov_regression.MarkovRegression`](generated/statsmodels.tsa.regime_switching.markov_regression.markovregression#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression")(β¦) | First-order k-regime Markov switching regression model |
| [`regime_switching.markov_autoregression.MarkovAutoregression`](generated/statsmodels.tsa.regime_switching.markov_autoregression.markovautoregression#statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression "statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression")(β¦) | Markov switching regression model |
ARMA Process
------------
The following are tools to work with the theoretical properties of an ARMA process for given lag-polynomials.
| | |
| --- | --- |
| [`arima_process.ArmaProcess`](generated/statsmodels.tsa.arima_process.armaprocess#statsmodels.tsa.arima_process.ArmaProcess "statsmodels.tsa.arima_process.ArmaProcess")([ar, ma, nobs]) | Theoretical properties of an ARMA process for specified lag-polynomials |
| [`arima_process.ar2arma`](generated/statsmodels.tsa.arima_process.ar2arma#statsmodels.tsa.arima_process.ar2arma "statsmodels.tsa.arima_process.ar2arma")(ar\_des, p, q[, n, β¦]) | Find arma approximation to ar process |
| [`arima_process.arma2ar`](generated/statsmodels.tsa.arima_process.arma2ar#statsmodels.tsa.arima_process.arma2ar "statsmodels.tsa.arima_process.arma2ar")(ar, ma[, lags]) | Get the AR representation of an ARMA process |
| [`arima_process.arma2ma`](generated/statsmodels.tsa.arima_process.arma2ma#statsmodels.tsa.arima_process.arma2ma "statsmodels.tsa.arima_process.arma2ma")(ar, ma[, lags]) | Get the MA representation of an ARMA process |
| [`arima_process.arma_acf`](generated/statsmodels.tsa.arima_process.arma_acf#statsmodels.tsa.arima_process.arma_acf "statsmodels.tsa.arima_process.arma_acf")(ar, ma[, lags]) | Theoretical autocorrelation function of an ARMA process |
| [`arima_process.arma_acovf`](generated/statsmodels.tsa.arima_process.arma_acovf#statsmodels.tsa.arima_process.arma_acovf "statsmodels.tsa.arima_process.arma_acovf")(ar, ma[, nobs]) | Theoretical autocovariance function of ARMA process |
| [`arima_process.arma_generate_sample`](generated/statsmodels.tsa.arima_process.arma_generate_sample#statsmodels.tsa.arima_process.arma_generate_sample "statsmodels.tsa.arima_process.arma_generate_sample")(ar, ma, β¦) | Generate a random sample of an ARMA process |
| [`arima_process.arma_impulse_response`](generated/statsmodels.tsa.arima_process.arma_impulse_response#statsmodels.tsa.arima_process.arma_impulse_response "statsmodels.tsa.arima_process.arma_impulse_response")(ar, ma) | Get the impulse response function (MA representation) for ARMA process |
| [`arima_process.arma_pacf`](generated/statsmodels.tsa.arima_process.arma_pacf#statsmodels.tsa.arima_process.arma_pacf "statsmodels.tsa.arima_process.arma_pacf")(ar, ma[, lags]) | Partial autocorrelation function of an ARMA process |
| [`arima_process.arma_periodogram`](generated/statsmodels.tsa.arima_process.arma_periodogram#statsmodels.tsa.arima_process.arma_periodogram "statsmodels.tsa.arima_process.arma_periodogram")(ar, ma[, β¦]) | Periodogram for ARMA process given by lag-polynomials ar and ma |
| [`arima_process.deconvolve`](generated/statsmodels.tsa.arima_process.deconvolve#statsmodels.tsa.arima_process.deconvolve "statsmodels.tsa.arima_process.deconvolve")(num, den[, n]) | Deconvolves divisor out of signal, division of polynomials for n terms |
| [`arima_process.index2lpol`](generated/statsmodels.tsa.arima_process.index2lpol#statsmodels.tsa.arima_process.index2lpol "statsmodels.tsa.arima_process.index2lpol")(coeffs, index) | Expand coefficients to lag poly |
| [`arima_process.lpol2index`](generated/statsmodels.tsa.arima_process.lpol2index#statsmodels.tsa.arima_process.lpol2index "statsmodels.tsa.arima_process.lpol2index")(ar) | Remove zeros from lag polynomial |
| [`arima_process.lpol_fiar`](generated/statsmodels.tsa.arima_process.lpol_fiar#statsmodels.tsa.arima_process.lpol_fiar "statsmodels.tsa.arima_process.lpol_fiar")(d[, n]) | AR representation of fractional integration |
| [`arima_process.lpol_fima`](generated/statsmodels.tsa.arima_process.lpol_fima#statsmodels.tsa.arima_process.lpol_fima "statsmodels.tsa.arima_process.lpol_fima")(d[, n]) | MA representation of fractional integration |
| [`arima_process.lpol_sdiff`](generated/statsmodels.tsa.arima_process.lpol_sdiff#statsmodels.tsa.arima_process.lpol_sdiff "statsmodels.tsa.arima_process.lpol_sdiff")(s) | return coefficients for seasonal difference (1-L^s) |
| | |
| --- | --- |
| [`sandbox.tsa.fftarma.ArmaFft`](generated/statsmodels.sandbox.tsa.fftarma.armafft#statsmodels.sandbox.tsa.fftarma.ArmaFft "statsmodels.sandbox.tsa.fftarma.ArmaFft")(ar, ma, n) | fft tools for arma processes |
Time Series Filters
-------------------
| | |
| --- | --- |
| [`filters.bk_filter.bkfilter`](generated/statsmodels.tsa.filters.bk_filter.bkfilter#statsmodels.tsa.filters.bk_filter.bkfilter "statsmodels.tsa.filters.bk_filter.bkfilter")(X[, low, high, K]) | Baxter-King bandpass filter |
| [`filters.hp_filter.hpfilter`](generated/statsmodels.tsa.filters.hp_filter.hpfilter#statsmodels.tsa.filters.hp_filter.hpfilter "statsmodels.tsa.filters.hp_filter.hpfilter")(X[, lamb]) | Hodrick-Prescott filter |
| [`filters.cf_filter.cffilter`](generated/statsmodels.tsa.filters.cf_filter.cffilter#statsmodels.tsa.filters.cf_filter.cffilter "statsmodels.tsa.filters.cf_filter.cffilter")(X[, low, high, drift]) | Christiano Fitzgerald asymmetric, random walk filter |
| [`filters.filtertools.convolution_filter`](generated/statsmodels.tsa.filters.filtertools.convolution_filter#statsmodels.tsa.filters.filtertools.convolution_filter "statsmodels.tsa.filters.filtertools.convolution_filter")(x, filt) | Linear filtering via convolution. |
| [`filters.filtertools.recursive_filter`](generated/statsmodels.tsa.filters.filtertools.recursive_filter#statsmodels.tsa.filters.filtertools.recursive_filter "statsmodels.tsa.filters.filtertools.recursive_filter")(x, ar\_coeff) | Autoregressive, or recursive, filtering. |
| [`filters.filtertools.miso_lfilter`](generated/statsmodels.tsa.filters.filtertools.miso_lfilter#statsmodels.tsa.filters.filtertools.miso_lfilter "statsmodels.tsa.filters.filtertools.miso_lfilter")(ar, ma, x) | use nd convolution to merge inputs, then use lfilter to produce output |
| [`filters.filtertools.fftconvolve3`](generated/statsmodels.tsa.filters.filtertools.fftconvolve3#statsmodels.tsa.filters.filtertools.fftconvolve3 "statsmodels.tsa.filters.filtertools.fftconvolve3")(in1[, in2, β¦]) | Convolve two N-dimensional arrays using FFT. |
| [`filters.filtertools.fftconvolveinv`](generated/statsmodels.tsa.filters.filtertools.fftconvolveinv#statsmodels.tsa.filters.filtertools.fftconvolveinv "statsmodels.tsa.filters.filtertools.fftconvolveinv")(in1, in2) | Convolve two N-dimensional arrays using FFT. |
| [`seasonal.seasonal_decompose`](generated/statsmodels.tsa.seasonal.seasonal_decompose#statsmodels.tsa.seasonal.seasonal_decompose "statsmodels.tsa.seasonal.seasonal_decompose")(x[, model, β¦]) | Seasonal decomposition using moving averages |
TSA Tools
---------
| | |
| --- | --- |
| [`tsatools.add_trend`](generated/statsmodels.tsa.tsatools.add_trend#statsmodels.tsa.tsatools.add_trend "statsmodels.tsa.tsatools.add_trend")(x[, trend, prepend, β¦]) | Adds a trend and/or constant to an array. |
| [`tsatools.detrend`](generated/statsmodels.tsa.tsatools.detrend#statsmodels.tsa.tsatools.detrend "statsmodels.tsa.tsatools.detrend")(x[, order, axis]) | Detrend an array with a trend of given order along axis 0 or 1 |
| [`tsatools.lagmat`](generated/statsmodels.tsa.tsatools.lagmat#statsmodels.tsa.tsatools.lagmat "statsmodels.tsa.tsatools.lagmat")(x, maxlag[, trim, original, β¦]) | Create 2d array of lags |
| [`tsatools.lagmat2ds`](generated/statsmodels.tsa.tsatools.lagmat2ds#statsmodels.tsa.tsatools.lagmat2ds "statsmodels.tsa.tsatools.lagmat2ds")(x, maxlag0[, maxlagex, β¦]) | Generate lagmatrix for 2d array, columns arranged by variables |
VARMA Process
-------------
| | |
| --- | --- |
| [`varma_process.VarmaPoly`](generated/statsmodels.tsa.varma_process.varmapoly#statsmodels.tsa.varma_process.VarmaPoly "statsmodels.tsa.varma_process.VarmaPoly")(ar[, ma]) | class to keep track of Varma polynomial format |
Interpolation
-------------
| | |
| --- | --- |
| [`interp.denton.dentonm`](generated/statsmodels.tsa.interp.denton.dentonm#statsmodels.tsa.interp.denton.dentonm "statsmodels.tsa.interp.denton.dentonm")(indicator, benchmark) | Modified Dentonβs method to convert low-frequency to high-frequency data. |
| programming_docs |
statsmodels Other Models miscmodels Other Models miscmodels
=======================
[`statsmodels.miscmodels`](#module-statsmodels.miscmodels "statsmodels.miscmodels") contains model classes and that do not yet fit into any other category, or are basic implementations that are not yet polished and will most likely still change. Some of these models were written as examples for the generic maximum likelihood framework, and there will be others that might be based on general method of moments.
The models in this category have been checked for basic cases, but might be more exposed to numerical problems than the complete implementation. For example, count.Poisson has been added using only the generic maximum likelihood framework, the standard errors are based on the numerical evaluation of the Hessian, while discretemod.Poisson uses analytical Gradients and Hessian and will be more precise, especially in cases when there is strong multicollinearity. On the other hand, by subclassing GenericLikelihoodModel, it is easy to add new models, another example can be seen in the zero inflated Poisson model, miscmodels.count.
Count Models `count`
--------------------
| | |
| --- | --- |
| [`PoissonGMLE`](generated/statsmodels.miscmodels.count.poissongmle#statsmodels.miscmodels.count.PoissonGMLE "statsmodels.miscmodels.count.PoissonGMLE")(endog[, exog, loglike, score, β¦]) | Maximum Likelihood Estimation of Poisson Model |
| [`PoissonOffsetGMLE`](generated/statsmodels.miscmodels.count.poissonoffsetgmle#statsmodels.miscmodels.count.PoissonOffsetGMLE "statsmodels.miscmodels.count.PoissonOffsetGMLE")(endog[, exog, offset, missing]) | Maximum Likelihood Estimation of Poisson Model |
| [`PoissonZiGMLE`](generated/statsmodels.miscmodels.count.poissonzigmle#statsmodels.miscmodels.count.PoissonZiGMLE "statsmodels.miscmodels.count.PoissonZiGMLE")(endog[, exog, offset, missing]) | Maximum Likelihood Estimation of Poisson Model |
Linear Model with t-distributed errors
--------------------------------------
This is a class that shows that a new model can be defined by only specifying the method for the loglikelihood. All result statistics are inherited from the generic likelihood model and result classes. The results have been checked against R for a simple case.
| | |
| --- | --- |
| [`TLinearModel`](generated/statsmodels.miscmodels.tmodel.tlinearmodel#statsmodels.miscmodels.tmodel.TLinearModel "statsmodels.miscmodels.tmodel.TLinearModel")(endog[, exog, loglike, score, β¦]) | Maximum Likelihood Estimation of Linear Model with t-distributed errors |
statsmodels Time Series Analysis by State Space Methods statespace Time Series Analysis by State Space Methods statespace
======================================================
[`statsmodels.tsa.statespace`](#module-statsmodels.tsa.statespace "statsmodels.tsa.statespace: Statespace models for time-series analysis") contains classes and functions that are useful for time series analysis using state space methods.
A general state space model is of the form
\[\begin{split}y\_t & = Z\_t \alpha\_t + d\_t + \varepsilon\_t \\ \alpha\_t & = T\_t \alpha\_{t-1} + c\_t + R\_t \eta\_t \\\end{split}\] where \(y\_t\) refers to the observation vector at time \(t\), \(\alpha\_t\) refers to the (unobserved) state vector at time \(t\), and where the irregular components are defined as
\[\begin{split}\varepsilon\_t \sim N(0, H\_t) \\ \eta\_t \sim N(0, Q\_t) \\\end{split}\] The remaining variables (\(Z\_t, d\_t, H\_t, T\_t, c\_t, R\_t, Q\_t\)) in the equations are matrices describing the process. Their variable names and dimensions are as follows
Z : `design` \((k\\_endog \times k\\_states \times nobs)\)
d : `obs_intercept` \((k\\_endog \times nobs)\)
H : `obs_cov` \((k\\_endog \times k\\_endog \times nobs)\)
T : `transition` \((k\\_states \times k\\_states \times nobs)\)
c : `state_intercept` \((k\\_states \times nobs)\)
R : `selection` \((k\\_states \times k\\_posdef \times nobs)\)
Q : `state_cov` \((k\\_posdef \times k\\_posdef \times nobs)\)
In the case that one of the matrices is time-invariant (so that, for example, \(Z\_t = Z\_{t+1} ~ \forall ~ t\)), its last dimension may be of size \(1\) rather than size `nobs`.
This generic form encapsulates many of the most popular linear time series models (see below) and is very flexible, allowing estimation with missing observations, forecasting, impulse response functions, and much more.
Example: AR(2) model
--------------------
An autoregressive model is a good introductory example to putting models in state space form. Recall that an AR(2) model is often written as:
\[y\_t = \phi\_1 y\_{t-1} + \phi\_2 y\_{t-2} + \epsilon\_t\] This can be put into state space form in the following way:
\[\begin{split}y\_t & = \begin{bmatrix} 1 & 0 \end{bmatrix} \alpha\_t \\ \alpha\_t & = \begin{bmatrix} \phi\_1 & \phi\_2 \\ 1 & 0 \end{bmatrix} \alpha\_{t-1} + \begin{bmatrix} 1 \\ 0 \end{bmatrix} \eta\_t\end{split}\] Where
\[Z\_t \equiv Z = \begin{bmatrix} 1 & 0 \end{bmatrix}\] and
\[\begin{split}T\_t \equiv T & = \begin{bmatrix} \phi\_1 & \phi\_2 \\ 1 & 0 \end{bmatrix} \\ R\_t \equiv R & = \begin{bmatrix} 1 \\ 0 \end{bmatrix} \\ \eta\_t & \sim N(0, \sigma^2)\end{split}\] There are three unknown parameters in this model: \(\phi\_1, \phi\_2, \sigma^2\).
### Models and Estimation
The following are the main estimation classes, which can be accessed through `statsmodels.tsa.statespace.api` and their result classes.
Seasonal Autoregressive Integrated Moving-Average with eXogenous regressors (SARIMAX)
-------------------------------------------------------------------------------------
The `SARIMAX` class is an example of a fully fledged model created using the statespace backend for estimation. `SARIMAX` can be used very similarly to [tsa](tsa#tsa) models, but works on a wider range of models by adding the estimation of additive and multiplicative seasonal effects, as well as arbitrary trend polynomials.
| | |
| --- | --- |
| [`sarimax.SARIMAX`](generated/statsmodels.tsa.statespace.sarimax.sarimax#statsmodels.tsa.statespace.sarimax.SARIMAX "statsmodels.tsa.statespace.sarimax.SARIMAX")(endog[, exog, order, β¦]) | Seasonal AutoRegressive Integrated Moving Average with eXogenous regressors model |
| [`sarimax.SARIMAXResults`](generated/statsmodels.tsa.statespace.sarimax.sarimaxresults#statsmodels.tsa.statespace.sarimax.SARIMAXResults "statsmodels.tsa.statespace.sarimax.SARIMAXResults")(model, params, β¦[, β¦]) | Class to hold results from fitting an SARIMAX model. |
For an example of the use of this model, see the [SARIMAX example notebook](examples/notebooks/generated/statespace_sarimax_stata) or the very brief code snippet below:
```
# Load the statsmodels api
import statsmodels.api as sm
# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')
# We could fit an AR(2) model, described above
mod_ar2 = sm.tsa.SARIMAX(endog, order=(2,0,0))
# Note that mod_ar2 is an instance of the SARIMAX class
# Fit the model via maximum likelihood
res_ar2 = mod_ar2.fit()
# Note that res_ar2 is an instance of the SARIMAXResults class
# Show the summary of results
print(res_ar2.summary())
# We could also fit a more complicated model with seasonal components.
# As an example, here is an SARIMA(1,1,1) x (0,1,1,4):
mod_sarimax = sm.tsa.SARIMAX(endog, order=(1,1,1),
seasonal_order=(0,1,1,4))
res_sarimax = mod_sarimax.fit()
# Show the summary of results
print(res_sarimax.summary())
```
The results object has many of the attributes and methods you would expect from other Statsmodels results objects, including standard errors, z-statistics, and prediction / forecasting.
Behind the scenes, the `SARIMAX` model creates the design and transition matrices (and sometimes some of the other matrices) based on the model specification.
Unobserved Components
---------------------
The `UnobservedComponents` class is another example of a statespace model.
| | |
| --- | --- |
| [`structural.UnobservedComponents`](generated/statsmodels.tsa.statespace.structural.unobservedcomponents#statsmodels.tsa.statespace.structural.UnobservedComponents "statsmodels.tsa.statespace.structural.UnobservedComponents")(endog[, β¦]) | Univariate unobserved components time series model |
| [`structural.UnobservedComponentsResults`](generated/statsmodels.tsa.statespace.structural.unobservedcomponentsresults#statsmodels.tsa.statespace.structural.UnobservedComponentsResults "statsmodels.tsa.statespace.structural.UnobservedComponentsResults")(β¦) | Class to hold results from fitting an unobserved components model. |
For examples of the use of this model, see the [example notebook](examples/notebooks/generated/statespace_structural_harvey_jaeger) or a notebook on using the unobserved components model to [decompose a time series into a trend and cycle](examples/notebooks/generated/statespace_cycles) or the very brief code snippet below:
```
# Load the statsmodels api
import statsmodels.api as sm
# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')
# Fit a local level model
mod_ll = sm.tsa.UnobservedComponents(endog, 'local level')
# Note that mod_ll is an instance of the UnobservedComponents class
# Fit the model via maximum likelihood
res_ll = mod_ll.fit()
# Note that res_ll is an instance of the UnobservedComponentsResults class
# Show the summary of results
print(res_ll.summary())
# Show a plot of the estimated level and trend component series
fig_ll = res_ll.plot_components()
# We could further add a damped stochastic cycle as follows
mod_cycle = sm.tsa.UnobservedComponents(endog, 'local level', cycle=True,
damped_cycle=true,
stochastic_cycle=True)
res_cycle = mod_cycle.fit()
# Show the summary of results
print(res_cycle.summary())
# Show a plot of the estimated level, trend, and cycle component series
fig_cycle = res_cycle.plot_components()
```
Vector Autoregressive Moving-Average with eXogenous regressors (VARMAX)
-----------------------------------------------------------------------
The `VARMAX` class is an example of a multivariate statespace model.
| | |
| --- | --- |
| [`varmax.VARMAX`](generated/statsmodels.tsa.statespace.varmax.varmax#statsmodels.tsa.statespace.varmax.VARMAX "statsmodels.tsa.statespace.varmax.VARMAX")(endog[, exog, order, trend, β¦]) | Vector Autoregressive Moving Average with eXogenous regressors model |
| [`varmax.VARMAXResults`](generated/statsmodels.tsa.statespace.varmax.varmaxresults#statsmodels.tsa.statespace.varmax.VARMAXResults "statsmodels.tsa.statespace.varmax.VARMAXResults")(model, params, β¦[, β¦]) | Class to hold results from fitting an VARMAX model. |
For an example of the use of this model, see the [VARMAX example notebook](examples/notebooks/generated/statespace_varmax) or the very brief code snippet below:
```
# Load the statsmodels api
import statsmodels.api as sm
# Load your (multivariate) dataset
endog = pd.read_csv('your/dataset/here.csv')
# Fit a local level model
mod_var1 = sm.tsa.VARMAX(endog, order=(1,0))
# Note that mod_var1 is an instance of the VARMAX class
# Fit the model via maximum likelihood
res_var1 = mod_var1.fit()
# Note that res_var1 is an instance of the VARMAXResults class
# Show the summary of results
print(res_var1.summary())
# Construct impulse responses
irfs = res_ll.impulse_responses(steps=10)
```
Dynamic Factor Models
---------------------
The `DynamicFactor` class is another example of a multivariate statespace model.
| | |
| --- | --- |
| [`dynamic_factor.DynamicFactor`](generated/statsmodels.tsa.statespace.dynamic_factor.dynamicfactor#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor")(endog, β¦[, β¦]) | Dynamic factor model |
| [`dynamic_factor.DynamicFactorResults`](generated/statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults")(model, β¦) | Class to hold results from fitting an DynamicFactor model. |
For an example of the use of this model, see the [Dynamic Factor example notebook](examples/notebooks/generated/statespace_dfm_coincident) or the very brief code snippet below:
```
# Load the statsmodels api
import statsmodels.api as sm
# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')
# Fit a local level model
mod_dfm = sm.tsa.DynamicFactor(endog, k_factors=1, factor_order=2)
# Note that mod_dfm is an instance of the DynamicFactor class
# Fit the model via maximum likelihood
res_dfm = mod_dfm.fit()
# Note that res_dfm is an instance of the DynamicFactorResults class
# Show the summary of results
print(res_ll.summary())
# Show a plot of the r^2 values from regressions of
# individual estimated factors on endogenous variables.
fig_dfm = res_ll.plot_coefficients_of_determination()
```
Custom state space models
-------------------------
The true power of the state space model is to allow the creation and estimation of custom models. Usually that is done by extending the following two classes, which bundle all of state space representation, Kalman filtering, and maximum likelihood fitting functionality for estimation and results output.
| | |
| --- | --- |
| [`mlemodel.MLEModel`](generated/statsmodels.tsa.statespace.mlemodel.mlemodel#statsmodels.tsa.statespace.mlemodel.MLEModel "statsmodels.tsa.statespace.mlemodel.MLEModel")(endog, k\_states[, exog, β¦]) | State space model for maximum likelihood estimation |
| [`mlemodel.MLEResults`](generated/statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults")(model, params, results) | Class to hold results from fitting a state space model. |
For a basic example demonstrating creating and estimating a custom state space model, see the [Local Linear Trend example notebook](examples/notebooks/generated/statespace_local_linear_trend). For a more sophisticated example, see the source code for the `SARIMAX` and `SARIMAXResults` classes, which are built by extending `MLEModel` and `MLEResults`.
In simple cases, the model can be constructed entirely using the MLEModel class. For example, the AR(2) model from above could be constructed and estimated using only the following code:
```
import numpy as np
from scipy.signal import lfilter
import statsmodels.api as sm
# True model parameters
nobs = int(1e3)
true_phi = np.r_[0.5, -0.2]
true_sigma = 1**0.5
# Simulate a time series
np.random.seed(1234)
disturbances = np.random.normal(0, true_sigma, size=(nobs,))
endog = lfilter([1], np.r_[1, -true_phi], disturbances)
# Construct the model
class AR2(sm.tsa.statespace.MLEModel):
def __init__(self, endog):
# Initialize the state space model
super(AR2, self).__init__(endog, k_states=2, k_posdef=1,
initialization='stationary')
# Setup the fixed components of the state space representation
self['design'] = [1, 0]
self['transition'] = [[0, 0],
[1, 0]]
self['selection', 0, 0] = 1
# Describe how parameters enter the model
def update(self, params, transformed=True, **kwargs):
params = super(AR2, self).update(params, transformed, **kwargs)
self['transition', 0, :] = params[:2]
self['state_cov', 0, 0] = params[2]
# Specify start parameters and parameter names
@property
def start_params(self):
return [0,0,1] # these are very simple
# Create and fit the model
mod = AR2(endog)
res = mod.fit()
print(res.summary())
```
This results in the following summary table:
```
Statespace Model Results
==============================================================================
Dep. Variable: y No. Observations: 1000
Model: AR2 Log Likelihood -1389.437
Date: Wed, 26 Oct 2016 AIC 2784.874
Time: 00:42:03 BIC 2799.598
Sample: 0 HQIC 2790.470
- 1000
Covariance Type: opg
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
param.0 0.4395 0.030 14.730 0.000 0.381 0.498
param.1 -0.2055 0.032 -6.523 0.000 -0.267 -0.144
param.2 0.9425 0.042 22.413 0.000 0.860 1.025
===================================================================================
Ljung-Box (Q): 24.25 Jarque-Bera (JB): 0.22
Prob(Q): 0.98 Prob(JB): 0.90
Heteroskedasticity (H): 1.05 Skew: -0.04
Prob(H) (two-sided): 0.66 Kurtosis: 3.02
===================================================================================
Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).
```
The results object has many of the attributes and methods you would expect from other Statsmodels results objects, including standard errors, z-statistics, and prediction / forecasting.
More advanced usage is possible, including specifying parameter transformations, and specifing names for parameters for a more informative output summary.
State space representation and Kalman filtering
-----------------------------------------------
While creation of custom models will almost always be done by extending `MLEModel` and `MLEResults`, it can be useful to understand the superstructure behind those classes.
Maximum likelihood estimation requires evaluating the likelihood function of the model, and for models in state space form the likelihood function is evaluted as a byproduct of running the Kalman filter.
There are two classes used by `MLEModel` that facilitate specification of the state space model and Kalman filtering: `Representation` and `KalmanFilter`.
The `Representation` class is the piece where the state space model representation is defined. In simple terms, it holds the state space matrices (`design`, `obs_intercept`, etc.; see the introduction to state space models, above) and allows their manipulation.
`FrozenRepresentation` is the most basic results-type class, in that it takes a βsnapshotβ of the state space representation at any given time. See the class documentation for the full list of available attributes.
| | |
| --- | --- |
| [`representation.Representation`](generated/statsmodels.tsa.statespace.representation.representation#statsmodels.tsa.statespace.representation.Representation "statsmodels.tsa.statespace.representation.Representation")(k\_endog, k\_states) | State space representation of a time series process |
| [`representation.FrozenRepresentation`](generated/statsmodels.tsa.statespace.representation.frozenrepresentation#statsmodels.tsa.statespace.representation.FrozenRepresentation "statsmodels.tsa.statespace.representation.FrozenRepresentation")(model) | Frozen Statespace Model |
The `KalmanFilter` class is a subclass of Representation that provides filtering capabilities. Once the state space representation matrices have been constructed, the [`filter`](generated/statsmodels.tsa.statespace.kalman_filter.kalmanfilter.filter#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.filter "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.filter") method can be called, producing a `FilterResults` instance; `FilterResults` is a subclass of `FrozenRepresentation`.
The `FilterResults` class not only holds a frozen representation of the state space model (the design, transition, etc. matrices, as well as model dimensions, etc.) but it also holds the filtering output, including the [`filtered state`](generated/statsmodels.tsa.statespace.kalman_filter.filterresults#statsmodels.tsa.statespace.kalman_filter.FilterResults.filtered_state "statsmodels.tsa.statespace.kalman_filter.FilterResults.filtered_state") and loglikelihood (see the class documentation for the full list of available results). It also provides a [`predict`](generated/statsmodels.tsa.statespace.kalman_filter.filterresults.predict#statsmodels.tsa.statespace.kalman_filter.FilterResults.predict "statsmodels.tsa.statespace.kalman_filter.FilterResults.predict") method, which allows in-sample prediction or out-of-sample forecasting. A similar method, `predict`, provides additional prediction or forecasting results, including confidence intervals.
| | |
| --- | --- |
| [`kalman_filter.KalmanFilter`](generated/statsmodels.tsa.statespace.kalman_filter.kalmanfilter#statsmodels.tsa.statespace.kalman_filter.KalmanFilter "statsmodels.tsa.statespace.kalman_filter.KalmanFilter")(k\_endog, k\_states) | State space representation of a time series process, with Kalman filter |
| [`kalman_filter.FilterResults`](generated/statsmodels.tsa.statespace.kalman_filter.filterresults#statsmodels.tsa.statespace.kalman_filter.FilterResults "statsmodels.tsa.statespace.kalman_filter.FilterResults")(model) | Results from applying the Kalman filter to a state space model. |
| [`kalman_filter.PredictionResults`](generated/statsmodels.tsa.statespace.kalman_filter.predictionresults#statsmodels.tsa.statespace.kalman_filter.PredictionResults "statsmodels.tsa.statespace.kalman_filter.PredictionResults")(results, β¦) | Results of in-sample and out-of-sample prediction for state space models generally |
The `KalmanSmoother` class is a subclass of `KalmanFilter` that provides smoothing capabilities. Once the state space representation matrices have been constructed, the `filter` method can be called, producing a `SmootherResults` instance; `SmootherResults` is a subclass of `FilterResults`.
The `SmootherResults` class holds all the output from `FilterResults`, but also includes smoothing output, including the `smoothed state` and loglikelihood (see the class documentation for the full list of available results). Whereas βfilteredβ output at time `t` refers to estimates conditional on observations up through time `t`, βsmoothedβ output refers to estimates conditional on the entire set of observations in the dataset.
| | |
| --- | --- |
| [`kalman_smoother.KalmanSmoother`](generated/statsmodels.tsa.statespace.kalman_smoother.kalmansmoother#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother "statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother")(k\_endog, k\_states) | State space representation of a time series process, with Kalman filter and smoother. |
| [`kalman_smoother.SmootherResults`](generated/statsmodels.tsa.statespace.kalman_smoother.smootherresults#statsmodels.tsa.statespace.kalman_smoother.SmootherResults "statsmodels.tsa.statespace.kalman_smoother.SmootherResults")(model) | Results from applying the Kalman smoother and/or filter to a state space model. |
### Statespace diagnostics
Three diagnostic tests are available after estimation of any statespace model, whether built in or custom, to help assess whether the model conforms to the underlying statistical assumptions. These tests are:
* [`test_normality`](generated/statsmodels.tsa.statespace.mlemodel.mleresults.test_normality#statsmodels.tsa.statespace.mlemodel.MLEResults.test_normality "statsmodels.tsa.statespace.mlemodel.MLEResults.test_normality")
* [`test_heteroskedasticity`](generated/statsmodels.tsa.statespace.mlemodel.mleresults.test_heteroskedasticity#statsmodels.tsa.statespace.mlemodel.MLEResults.test_heteroskedasticity "statsmodels.tsa.statespace.mlemodel.MLEResults.test_heteroskedasticity")
* [`test_serial_correlation`](generated/statsmodels.tsa.statespace.mlemodel.mleresults.test_serial_correlation#statsmodels.tsa.statespace.mlemodel.MLEResults.test_serial_correlation "statsmodels.tsa.statespace.mlemodel.MLEResults.test_serial_correlation")
A number of standard plots of regression residuals are available for the same purpose. These can be produced using the command [`plot_diagnostics`](generated/statsmodels.tsa.statespace.mlemodel.mleresults.plot_diagnostics#statsmodels.tsa.statespace.mlemodel.MLEResults.plot_diagnostics "statsmodels.tsa.statespace.mlemodel.MLEResults.plot_diagnostics").
### Statespace Tools
There are a variety of tools used for state space modeling or by the SARIMAX class:
| | |
| --- | --- |
| [`tools.companion_matrix`](generated/statsmodels.tsa.statespace.tools.companion_matrix#statsmodels.tsa.statespace.tools.companion_matrix "statsmodels.tsa.statespace.tools.companion_matrix")(polynomial) | Create a companion matrix |
| [`tools.diff`](generated/statsmodels.tsa.statespace.tools.diff#statsmodels.tsa.statespace.tools.diff "statsmodels.tsa.statespace.tools.diff")(series[, k\_diff, β¦]) | Difference a series simply and/or seasonally along the zero-th axis. |
| [`tools.is_invertible`](generated/statsmodels.tsa.statespace.tools.is_invertible#statsmodels.tsa.statespace.tools.is_invertible "statsmodels.tsa.statespace.tools.is_invertible")(polynomial[, threshold]) | Determine if a polynomial is invertible. |
| [`tools.constrain_stationary_univariate`](generated/statsmodels.tsa.statespace.tools.constrain_stationary_univariate#statsmodels.tsa.statespace.tools.constrain_stationary_univariate "statsmodels.tsa.statespace.tools.constrain_stationary_univariate")(β¦) | Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation |
| [`tools.unconstrain_stationary_univariate`](generated/statsmodels.tsa.statespace.tools.unconstrain_stationary_univariate#statsmodels.tsa.statespace.tools.unconstrain_stationary_univariate "statsmodels.tsa.statespace.tools.unconstrain_stationary_univariate")(β¦) | Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer |
| [`tools.constrain_stationary_multivariate`](generated/statsmodels.tsa.statespace.tools.constrain_stationary_multivariate#statsmodels.tsa.statespace.tools.constrain_stationary_multivariate "statsmodels.tsa.statespace.tools.constrain_stationary_multivariate")(β¦) | Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation for a vector autoregression. |
| [`tools.unconstrain_stationary_multivariate`](generated/statsmodels.tsa.statespace.tools.unconstrain_stationary_multivariate#statsmodels.tsa.statespace.tools.unconstrain_stationary_multivariate "statsmodels.tsa.statespace.tools.unconstrain_stationary_multivariate")(β¦) | Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer |
| [`tools.validate_matrix_shape`](generated/statsmodels.tsa.statespace.tools.validate_matrix_shape#statsmodels.tsa.statespace.tools.validate_matrix_shape "statsmodels.tsa.statespace.tools.validate_matrix_shape")(name, shape, β¦) | Validate the shape of a possibly time-varying matrix, or raise an exception |
| [`tools.validate_vector_shape`](generated/statsmodels.tsa.statespace.tools.validate_vector_shape#statsmodels.tsa.statespace.tools.validate_vector_shape "statsmodels.tsa.statespace.tools.validate_vector_shape")(name, shape, β¦) | Validate the shape of a possibly time-varying vector, or raise an exception |
| programming_docs |
statsmodels Graphics Graphics
========
Goodness of Fit Plots
---------------------
| | |
| --- | --- |
| [`gofplots.qqplot`](generated/statsmodels.graphics.gofplots.qqplot#statsmodels.graphics.gofplots.qqplot "statsmodels.graphics.gofplots.qqplot")(data[, dist, distargs, a, β¦]) | Q-Q plot of the quantiles of x versus the quantiles/ppf of a distribution. |
| [`gofplots.qqline`](generated/statsmodels.graphics.gofplots.qqline#statsmodels.graphics.gofplots.qqline "statsmodels.graphics.gofplots.qqline")(ax, line[, x, y, dist, fmt]) | Plot a reference line for a qqplot. |
| [`gofplots.qqplot_2samples`](generated/statsmodels.graphics.gofplots.qqplot_2samples#statsmodels.graphics.gofplots.qqplot_2samples "statsmodels.graphics.gofplots.qqplot_2samples")(data1, data2[, β¦]) | Q-Q Plot of two samplesβ quantiles. |
| [`gofplots.ProbPlot`](generated/statsmodels.graphics.gofplots.probplot#statsmodels.graphics.gofplots.ProbPlot "statsmodels.graphics.gofplots.ProbPlot")(data[, dist, fit, β¦]) | Class for convenient construction of Q-Q, P-P, and probability plots. |
Boxplots
--------
| | |
| --- | --- |
| [`boxplots.violinplot`](generated/statsmodels.graphics.boxplots.violinplot#statsmodels.graphics.boxplots.violinplot "statsmodels.graphics.boxplots.violinplot")(data[, ax, labels, β¦]) | Make a violin plot of each dataset in the `data` sequence. |
| [`boxplots.beanplot`](generated/statsmodels.graphics.boxplots.beanplot#statsmodels.graphics.boxplots.beanplot "statsmodels.graphics.boxplots.beanplot")(data[, ax, labels, β¦]) | Make a bean plot of each dataset in the `data` sequence. |
Correlation Plots
-----------------
| | |
| --- | --- |
| [`correlation.plot_corr`](generated/statsmodels.graphics.correlation.plot_corr#statsmodels.graphics.correlation.plot_corr "statsmodels.graphics.correlation.plot_corr")(dcorr[, xnames, β¦]) | Plot correlation of many variables in a tight color grid. |
| [`correlation.plot_corr_grid`](generated/statsmodels.graphics.correlation.plot_corr_grid#statsmodels.graphics.correlation.plot_corr_grid "statsmodels.graphics.correlation.plot_corr_grid")(dcorrs[, titles, β¦]) | Create a grid of correlation plots. |
| [`plot_grids.scatter_ellipse`](generated/statsmodels.graphics.plot_grids.scatter_ellipse#statsmodels.graphics.plot_grids.scatter_ellipse "statsmodels.graphics.plot_grids.scatter_ellipse")(data[, level, β¦]) | Create a grid of scatter plots with confidence ellipses. |
Functional Plots
----------------
| | |
| --- | --- |
| [`functional.hdrboxplot`](generated/statsmodels.graphics.functional.hdrboxplot#statsmodels.graphics.functional.hdrboxplot "statsmodels.graphics.functional.hdrboxplot")(data[, ncomp, alpha, β¦]) | High Density Region boxplot |
| [`functional.fboxplot`](generated/statsmodels.graphics.functional.fboxplot#statsmodels.graphics.functional.fboxplot "statsmodels.graphics.functional.fboxplot")(data[, xdata, labels, β¦]) | Plot functional boxplot. |
| [`functional.rainbowplot`](generated/statsmodels.graphics.functional.rainbowplot#statsmodels.graphics.functional.rainbowplot "statsmodels.graphics.functional.rainbowplot")(data[, xdata, depth, β¦]) | Create a rainbow plot for a set of curves. |
| [`functional.banddepth`](generated/statsmodels.graphics.functional.banddepth#statsmodels.graphics.functional.banddepth "statsmodels.graphics.functional.banddepth")(data[, method]) | Calculate the band depth for a set of functional curves. |
Regression Plots
----------------
| | |
| --- | --- |
| [`regressionplots.plot_fit`](generated/statsmodels.graphics.regressionplots.plot_fit#statsmodels.graphics.regressionplots.plot_fit "statsmodels.graphics.regressionplots.plot_fit")(results, exog\_idx) | Plot fit against one regressor. |
| [`regressionplots.plot_regress_exog`](generated/statsmodels.graphics.regressionplots.plot_regress_exog#statsmodels.graphics.regressionplots.plot_regress_exog "statsmodels.graphics.regressionplots.plot_regress_exog")(results, β¦) | Plot regression results against one regressor. |
| [`regressionplots.plot_partregress`](generated/statsmodels.graphics.regressionplots.plot_partregress#statsmodels.graphics.regressionplots.plot_partregress "statsmodels.graphics.regressionplots.plot_partregress")(endog, β¦) | Plot partial regression for a single regressor. |
| [`regressionplots.plot_ccpr`](generated/statsmodels.graphics.regressionplots.plot_ccpr#statsmodels.graphics.regressionplots.plot_ccpr "statsmodels.graphics.regressionplots.plot_ccpr")(results, exog\_idx) | Plot CCPR against one regressor. |
| [`regressionplots.abline_plot`](generated/statsmodels.graphics.regressionplots.abline_plot#statsmodels.graphics.regressionplots.abline_plot "statsmodels.graphics.regressionplots.abline_plot")([intercept, β¦]) | Plots a line given an intercept and slope. |
| [`regressionplots.influence_plot`](generated/statsmodels.graphics.regressionplots.influence_plot#statsmodels.graphics.regressionplots.influence_plot "statsmodels.graphics.regressionplots.influence_plot")(results[, β¦]) | Plot of influence in regression. |
| [`regressionplots.plot_leverage_resid2`](generated/statsmodels.graphics.regressionplots.plot_leverage_resid2#statsmodels.graphics.regressionplots.plot_leverage_resid2 "statsmodels.graphics.regressionplots.plot_leverage_resid2")(results) | Plots leverage statistics vs. |
Time Series Plots
-----------------
| | |
| --- | --- |
| [`tsaplots.plot_acf`](generated/statsmodels.graphics.tsaplots.plot_acf#statsmodels.graphics.tsaplots.plot_acf "statsmodels.graphics.tsaplots.plot_acf")(x[, ax, lags, alpha, β¦]) | Plot the autocorrelation function |
| [`tsaplots.plot_pacf`](generated/statsmodels.graphics.tsaplots.plot_pacf#statsmodels.graphics.tsaplots.plot_pacf "statsmodels.graphics.tsaplots.plot_pacf")(x[, ax, lags, alpha, β¦]) | Plot the partial autocorrelation function |
| [`tsaplots.month_plot`](generated/statsmodels.graphics.tsaplots.month_plot#statsmodels.graphics.tsaplots.month_plot "statsmodels.graphics.tsaplots.month_plot")(x[, dates, ylabel, ax]) | Seasonal plot of monthly data |
| [`tsaplots.quarter_plot`](generated/statsmodels.graphics.tsaplots.quarter_plot#statsmodels.graphics.tsaplots.quarter_plot "statsmodels.graphics.tsaplots.quarter_plot")(x[, dates, ylabel, ax]) | Seasonal plot of quarterly data |
Other Plots
-----------
| | |
| --- | --- |
| [`factorplots.interaction_plot`](generated/statsmodels.graphics.factorplots.interaction_plot#statsmodels.graphics.factorplots.interaction_plot "statsmodels.graphics.factorplots.interaction_plot")(x, trace, response) | Interaction plot for factor level statistics. |
| [`mosaicplot.mosaic`](generated/statsmodels.graphics.mosaicplot.mosaic#statsmodels.graphics.mosaicplot.mosaic "statsmodels.graphics.mosaicplot.mosaic")(data[, index, ax, β¦]) | Create a mosaic plot from a contingency table. |
| [`agreement.mean_diff_plot`](generated/statsmodels.graphics.agreement.mean_diff_plot#statsmodels.graphics.agreement.mean_diff_plot "statsmodels.graphics.agreement.mean_diff_plot")(m1, m2[, sd\_limit, β¦]) | Tukeyβs Mean Difference Plot. |
statsmodels Multivariate Statistics multivariate Multivariate Statistics multivariate
====================================
This section includes methods and algorithms from multivariate statistics.
Principal Component Analysis
----------------------------
| | |
| --- | --- |
| [`PCA`](generated/statsmodels.multivariate.pca.pca#statsmodels.multivariate.pca.PCA "statsmodels.multivariate.pca.PCA")(data[, ncomp, standardize, demean, β¦]) | Principal Component Analysis |
| `pca`(data[, ncomp, standardize, demean, β¦]) | Principal Component Analysis |
Factor Analysis
---------------
| | |
| --- | --- |
| [`Factor`](generated/statsmodels.multivariate.factor.factor#statsmodels.multivariate.factor.Factor "statsmodels.multivariate.factor.Factor")([endog, n\_factor, corr, method, smc, β¦]) | Factor analysis |
| [`FactorResults`](generated/statsmodels.multivariate.factor.factorresults#statsmodels.multivariate.factor.FactorResults "statsmodels.multivariate.factor.FactorResults")(factor) | Factor results class |
Factor Rotation
---------------
| | |
| --- | --- |
| [`rotate_factors`](generated/statsmodels.multivariate.factor_rotation.rotate_factors#statsmodels.multivariate.factor_rotation.rotate_factors "statsmodels.multivariate.factor_rotation.rotate_factors")(A, method, \*method\_args, β¦) | Subroutine for orthogonal and oblique rotation of the matrix \(A\). |
| [`target_rotation`](generated/statsmodels.multivariate.factor_rotation.target_rotation#statsmodels.multivariate.factor_rotation.target_rotation "statsmodels.multivariate.factor_rotation.target_rotation")(A, H[, full\_rank]) | Analytically performs orthogonal rotations towards a target matrix, i.e., we minimize: |
| [`procrustes`](generated/statsmodels.multivariate.factor_rotation.procrustes#statsmodels.multivariate.factor_rotation.procrustes "statsmodels.multivariate.factor_rotation.procrustes")(A, H) | Analytically solves the following Procrustes problem: |
| [`promax`](generated/statsmodels.multivariate.factor_rotation.promax#statsmodels.multivariate.factor_rotation.promax "statsmodels.multivariate.factor_rotation.promax")(A[, k]) | Performs promax rotation of the matrix \(A\). |
Canonical Correlation
---------------------
| | |
| --- | --- |
| [`CanCorr`](generated/statsmodels.multivariate.cancorr.cancorr#statsmodels.multivariate.cancorr.CanCorr "statsmodels.multivariate.cancorr.CanCorr")(endog, exog[, tolerance, missing, β¦]) | Canonical correlation analysis using singluar value decomposition |
MANOVA
------
| | |
| --- | --- |
| [`MANOVA`](generated/statsmodels.multivariate.manova.manova#statsmodels.multivariate.manova.MANOVA "statsmodels.multivariate.manova.MANOVA")(endog, exog[, missing, hasconst]) | Multivariate analysis of variance The implementation of MANOVA is based on multivariate regression and does not assume that the explanatory variables are categorical. |
MultivariateOLS
---------------
`_MultivariateOLS` is a model class with limited features. Currently it supports multivariate hypothesis tests and is used as backend for MANOVA.
| | |
| --- | --- |
| [`_MultivariateOLS`](generated/statsmodels.multivariate.multivariate_ols._multivariateols#statsmodels.multivariate.multivariate_ols._MultivariateOLS "statsmodels.multivariate.multivariate_ols._MultivariateOLS")(endog, exog[, missing, β¦]) | Multivariate linear model via least squares |
| [`_MultivariateOLSResults`](generated/statsmodels.multivariate.multivariate_ols._multivariateolsresults#statsmodels.multivariate.multivariate_ols._MultivariateOLSResults "statsmodels.multivariate.multivariate_ols._MultivariateOLSResults")(fitted\_mv\_ols) | \_MultivariateOLS results class |
| [`MultivariateTestResults`](generated/statsmodels.multivariate.multivariate_ols.multivariatetestresults#statsmodels.multivariate.multivariate_ols.MultivariateTestResults "statsmodels.multivariate.multivariate_ols.MultivariateTestResults")(mv\_test\_df, β¦) | Multivariate test results class Returned by `mv_test` method of `_MultivariateOLSResults` class |
statsmodels ANOVA ANOVA
=====
Analysis of Variance models containing anova\_lm for ANOVA analysis with a linear OLSModel, and AnovaRM for repeated measures ANOVA, within ANOVA for balanced data.
Examples
--------
```
In [1]: import statsmodels.api as sm
In [2]: from statsmodels.formula.api import ols
In [3]: moore = sm.datasets.get_rdataset("Moore", "car",
...: cache=True) # load data
...:
In [4]: data = moore.data
In [5]: data = data.rename(columns={"partner.status":
...: "partner_status"}) # make name pythonic
...:
In [6]: moore_lm = ols('conformity ~ C(fcategory, Sum)*C(partner_status, Sum)',
...: data=data).fit()
...:
In [7]: table = sm.stats.anova_lm(moore_lm, typ=2) # Type 2 ANOVA DataFrame
In [8]: print(table)
sum_sq df F \
C(fcategory, Sum) 11.614700 2.0 0.276958
C(partner_status, Sum) 212.213778 1.0 10.120692
C(fcategory, Sum):C(partner_status, Sum) 175.488928 2.0 4.184623
Residual 817.763961 39.0 NaN
PR(>F)
C(fcategory, Sum) 0.759564
C(partner_status, Sum) 0.002874
C(fcategory, Sum):C(partner_status, Sum) 0.022572
Residual NaN
```
A more detailed example for `anova_lm` can be found here:
* [ANOVA](examples/notebooks/generated/interactions_anova)
Module Reference
----------------
| | |
| --- | --- |
| [`anova_lm`](generated/statsmodels.stats.anova.anova_lm#statsmodels.stats.anova.anova_lm "statsmodels.stats.anova.anova_lm")(\*args, \*\*kwargs) | Anova table for one or more fitted linear models. |
| [`AnovaRM`](generated/statsmodels.stats.anova.anovarm#statsmodels.stats.anova.AnovaRM "statsmodels.stats.anova.AnovaRM")(data, depvar, subject[, within, β¦]) | Repeated measures Anova using least squares regression |
statsmodels Vector Autoregressions tsa.vector_ar Vector Autoregressions tsa.vector\_ar
=====================================
VAR(p) processes
----------------
We are interested in modeling a \(T \times K\) multivariate time series \(Y\), where \(T\) denotes the number of observations and \(K\) the number of variables. One way of estimating relationships between the time series and their lagged values is the *vector autoregression process*:
\[ \begin{align}\begin{aligned}Y\_t = A\_1 Y\_{t-1} + \ldots + A\_p Y\_{t-p} + u\_t\\u\_t \sim {\sf Normal}(0, \Sigma\_u)\end{aligned}\end{align} \] where \(A\_i\) is a \(K \times K\) coefficient matrix.
We follow in large part the methods and notation of [Lutkepohl (2005)](http://www.springer.com/gb/book/9783540401728), which we will not develop here.
### Model fitting
Note
The classes referenced below are accessible via the `statsmodels.tsa.api` module.
To estimate a VAR model, one must first create the model using an `ndarray` of homogeneous or structured dtype. When using a structured or record array, the class will use the passed variable names. Otherwise they can be passed explicitly:
```
# some example data
In [1]: import numpy as np
In [2]: import pandas
In [3]: import statsmodels.api as sm
In [4]: from statsmodels.tsa.api import VAR, DynamicVAR
In [5]: mdata = sm.datasets.macrodata.load_pandas().data
# prepare the dates index
In [6]: dates = mdata[['year', 'quarter']].astype(int).astype(str)
In [7]: quarterly = dates["year"] + "Q" + dates["quarter"]
In [8]: from statsmodels.tsa.base.datetools import dates_from_str
In [9]: quarterly = dates_from_str(quarterly)
In [10]: mdata = mdata[['realgdp','realcons','realinv']]
In [11]: mdata.index = pandas.DatetimeIndex(quarterly)
In [12]: data = np.log(mdata).diff().dropna()
# make a VAR model
In [13]: model = VAR(data)
```
Note
The [`VAR`](generated/statsmodels.tsa.vector_ar.var_model.var#statsmodels.tsa.vector_ar.var_model.VAR "statsmodels.tsa.vector_ar.var_model.VAR") class assumes that the passed time series are stationary. Non-stationary or trending data can often be transformed to be stationary by first-differencing or some other method. For direct analysis of non-stationary time series, a standard stable VAR(p) model is not appropriate.
To actually do the estimation, call the `fit` method with the desired lag order. Or you can have the model select a lag order based on a standard information criterion (see below):
```
In [14]: results = model.fit(2)
In [15]: results.summary()
Out[15]:
Summary of Regression Results
==================================
Model: VAR
Method: OLS
Date: Mon, 14, May, 2018
Time: 21:48:15
--------------------------------------------------------------------
No. of Equations: 3.00000 BIC: -27.5830
Nobs: 200.000 HQIC: -27.7892
Log likelihood: 1962.57 FPE: 7.42129e-13
AIC: -27.9293 Det(Omega_mle): 6.69358e-13
--------------------------------------------------------------------
Results for equation realgdp
==============================================================================
coefficient std. error t-stat prob
------------------------------------------------------------------------------
const 0.001527 0.001119 1.365 0.172
L1.realgdp -0.279435 0.169663 -1.647 0.100
L1.realcons 0.675016 0.131285 5.142 0.000
L1.realinv 0.033219 0.026194 1.268 0.205
L2.realgdp 0.008221 0.173522 0.047 0.962
L2.realcons 0.290458 0.145904 1.991 0.047
L2.realinv -0.007321 0.025786 -0.284 0.776
==============================================================================
Results for equation realcons
==============================================================================
coefficient std. error t-stat prob
------------------------------------------------------------------------------
const 0.005460 0.000969 5.634 0.000
L1.realgdp -0.100468 0.146924 -0.684 0.494
L1.realcons 0.268640 0.113690 2.363 0.018
L1.realinv 0.025739 0.022683 1.135 0.257
L2.realgdp -0.123174 0.150267 -0.820 0.412
L2.realcons 0.232499 0.126350 1.840 0.066
L2.realinv 0.023504 0.022330 1.053 0.293
==============================================================================
Results for equation realinv
==============================================================================
coefficient std. error t-stat prob
------------------------------------------------------------------------------
const -0.023903 0.005863 -4.077 0.000
L1.realgdp -1.970974 0.888892 -2.217 0.027
L1.realcons 4.414162 0.687825 6.418 0.000
L1.realinv 0.225479 0.137234 1.643 0.100
L2.realgdp 0.380786 0.909114 0.419 0.675
L2.realcons 0.800281 0.764416 1.047 0.295
L2.realinv -0.124079 0.135098 -0.918 0.358
==============================================================================
Correlation matrix of residuals
realgdp realcons realinv
realgdp 1.000000 0.603316 0.750722
realcons 0.603316 1.000000 0.131951
realinv 0.750722 0.131951 1.000000
```
Several ways to visualize the data using `matplotlib` are available.
Plotting input time series:
```
In [16]: results.plot()
Out[16]: <Figure size 1000x1000 with 3 Axes>
```
Plotting time series autocorrelation function:
```
In [17]: results.plot_acorr()
Out[17]: <Figure size 1000x1000 with 9 Axes>
```
### Lag order selection
Choice of lag order can be a difficult problem. Standard analysis employs likelihood test or information criteria-based order selection. We have implemented the latter, accessible through the [`VAR`](generated/statsmodels.tsa.vector_ar.var_model.var#statsmodels.tsa.vector_ar.var_model.VAR "statsmodels.tsa.vector_ar.var_model.VAR") class:
```
In [18]: model.select_order(15)
Out[18]: <statsmodels.tsa.vector_ar.var_model.LagOrderResults at 0x10c89fef0>
```
When calling the `fit` function, one can pass a maximum number of lags and the order criterion to use for order selection:
```
In [19]: results = model.fit(maxlags=15, ic='aic')
```
### Forecasting
The linear predictor is the optimal h-step ahead forecast in terms of mean-squared error:
\[y\_t(h) = \nu + A\_1 y\_t(h β 1) + \cdots + A\_p y\_t(h β p)\] We can use the `forecast` function to produce this forecast. Note that we have to specify the βinitial valueβ for the forecast:
```
In [20]: lag_order = results.k_ar
In [21]: results.forecast(data.values[-lag_order:], 5)
Out[21]:
array([[ 0.0062, 0.005 , 0.0092],
[ 0.0043, 0.0034, -0.0024],
[ 0.0042, 0.0071, -0.0119],
[ 0.0056, 0.0064, 0.0015],
[ 0.0063, 0.0067, 0.0038]])
```
The `forecast_interval` function will produce the above forecast along with asymptotic standard errors. These can be visualized using the `plot_forecast` function:
```
In [22]: results.plot_forecast(10)
Out[22]: <Figure size 1000x1000 with 3 Axes>
```
Impulse Response Analysis
-------------------------
*Impulse responses* are of interest in econometric studies: they are the estimated responses to a unit impulse in one of the variables. They are computed in practice using the MA(\(\infty\)) representation of the VAR(p) process:
\[Y\_t = \mu + \sum\_{i=0}^\infty \Phi\_i u\_{t-i}\] We can perform an impulse response analysis by calling the `irf` function on a `VARResults` object:
```
In [23]: irf = results.irf(10)
```
These can be visualized using the `plot` function, in either orthogonalized or non-orthogonalized form. Asymptotic standard errors are plotted by default at the 95% significance level, which can be modified by the user.
Note
Orthogonalization is done using the Cholesky decomposition of the estimated error covariance matrix \(\hat \Sigma\_u\) and hence interpretations may change depending on variable ordering.
```
In [24]: irf.plot(orth=False)
Out[24]: <Figure size 1000x1000 with 9 Axes>
```
Note the `plot` function is flexible and can plot only variables of interest if so desired:
```
In [25]: irf.plot(impulse='realgdp')
Out[25]: <Figure size 1000x1000 with 3 Axes>
```
The cumulative effects \(\Psi\_n = \sum\_{i=0}^n \Phi\_i\) can be plotted with the long run effects as follows:
```
In [26]: irf.plot_cum_effects(orth=False)
Out[26]: <Figure size 1000x1000 with 9 Axes>
```
Forecast Error Variance Decomposition (FEVD)
--------------------------------------------
Forecast errors of component j on k in an i-step ahead forecast can be decomposed using the orthogonalized impulse responses \(\Theta\_i\):
\[ \begin{align}\begin{aligned}\omega\_{jk, i} = \sum\_{i=0}^{h-1} (e\_j^\prime \Theta\_i e\_k)^2 / \mathrm{MSE}\_j(h)\\\mathrm{MSE}\_j(h) = \sum\_{i=0}^{h-1} e\_j^\prime \Phi\_i \Sigma\_u \Phi\_i^\prime e\_j\end{aligned}\end{align} \] These are computed via the `fevd` function up through a total number of steps ahead:
```
In [27]: fevd = results.fevd(5)
In [28]: fevd.summary()
FEVD for realgdp
realgdp realcons realinv
0 1.000000 0.000000 0.000000
1 0.864889 0.129253 0.005858
2 0.816725 0.177898 0.005378
3 0.793647 0.197590 0.008763
4 0.777279 0.208127 0.014594
FEVD for realcons
realgdp realcons realinv
0 0.359877 0.640123 0.000000
1 0.358767 0.635420 0.005813
2 0.348044 0.645138 0.006817
3 0.319913 0.653609 0.026478
4 0.317407 0.652180 0.030414
FEVD for realinv
realgdp realcons realinv
0 0.577021 0.152783 0.270196
1 0.488158 0.293622 0.218220
2 0.478727 0.314398 0.206874
3 0.477182 0.315564 0.207254
4 0.466741 0.324135 0.209124
```
They can also be visualized through the returned [`FEVD`](generated/statsmodels.tsa.vector_ar.var_model.fevd#statsmodels.tsa.vector_ar.var_model.FEVD "statsmodels.tsa.vector_ar.var_model.FEVD") object:
```
In [29]: results.fevd(20).plot()
Out[29]: <Figure size 1000x1000 with 3 Axes>
```
Statistical tests
-----------------
A number of different methods are provided to carry out hypothesis tests about the model results and also the validity of the model assumptions (normality, whiteness / βiid-nessβ of errors, etc.).
### Granger causality
One is often interested in whether a variable or group of variables is βcausalβ for another variable, for some definition of βcausalβ. In the context of VAR models, one can say that a set of variables are Granger-causal within one of the VAR equations. We will not detail the mathematics or definition of Granger causality, but leave it to the reader. The [`VARResults`](generated/statsmodels.tsa.vector_ar.var_model.varresults#statsmodels.tsa.vector_ar.var_model.VARResults "statsmodels.tsa.vector_ar.var_model.VARResults") object has the `test_causality` method for performing either a Wald (\(\chi^2\)) test or an F-test.
```
In [30]: results.test_causality('realgdp', ['realinv', 'realcons'], kind='f')
Out[30]: <statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults at 0x10ca15978>
```
### Normality
### Whiteness of residuals
Dynamic Vector Autoregressions
------------------------------
Note
To use this functionality, [pandas](https://pypi.python.org/pypi/pandas) must be installed. See the [pandas documentation](http://pandas.pydata.org) for more information on the below data structures.
One is often interested in estimating a moving-window regression on time series data for the purposes of making forecasts throughout the data sample. For example, we may wish to produce the series of 2-step-ahead forecasts produced by a VAR(p) model estimated at each point in time.
```
In [31]: np.random.seed(1)
In [32]: import pandas.util.testing as ptest
In [33]: ptest.N = 500
In [34]: data = ptest.makeTimeDataFrame().cumsum(0)
In [35]: data
Out[35]:
A B C D
2000-01-03 1.624345 -1.719394 -0.153236 1.301225
2000-01-04 1.012589 -1.662273 -2.585745 0.988833
2000-01-05 0.484417 -2.461821 -2.077760 0.717604
2000-01-06 -0.588551 -2.753416 -2.401793 2.580517
2000-01-07 0.276856 -3.012398 -3.912869 1.937644
... ... ... ... ...
2001-11-26 29.552085 14.274036 39.222558 -13.243907
2001-11-27 30.080964 11.996738 38.589968 -12.682989
2001-11-28 27.843878 11.927114 38.380121 -13.604648
2001-11-29 26.736165 12.280984 40.277282 -12.957273
2001-11-30 26.718447 12.094029 38.895890 -11.570447
[500 rows x 4 columns]
In [36]: var = DynamicVAR(data, lag_order=2, window_type='expanding')
```
The estimated coefficients for the dynamic model are returned as a [`pandas.Panel`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Panel.html#pandas.Panel "(in pandas v0.22.0)") object, which can allow you to easily examine, for example, all of the model coefficients by equation or by date:
```
In [37]: import datetime as dt
In [38]: var.coefs
Out[38]:
<class 'pandas.core.panel.Panel'>
Dimensions: 9 (items) x 489 (major_axis) x 4 (minor_axis)
Items axis: L1.A to intercept
Major_axis axis: 2000-01-18 00:00:00 to 2001-11-30 00:00:00
Minor_axis axis: A to D
# all estimated coefficients for equation A
In [39]: var.coefs.minor_xs('A').info()
```
| programming_docs |
statsmodels Import Paths and Structure Import Paths and Structure
==========================
We offer two ways of importing functions and classes from statsmodels:
1. [API import for interactive use](#api-import-for-interactive-use)
* Allows tab completion
2. [Direct import for programs](#direct-import-for-programs)
* Avoids importing unnecessary modules and commands
API Import for interactive use
------------------------------
For interactive use the recommended import is:
```
import statsmodels.api as sm
```
Importing `statsmodels.api` will load most of the public parts of statsmodels. This makes most functions and classes conveniently available within one or two levels, without making the βsmβ namespace too crowded.
To see what functions and classes available, you can type the following (or use the namespace exploration features of IPython, Spyder, IDLE, etc.):
```
>>> dir(sm)
['GLM', 'GLS', 'GLSAR', 'Logit', 'MNLogit', 'OLS', 'Poisson', 'Probit', 'RLM',
'WLS', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
'add_constant', 'categorical', 'datasets', 'distributions', 'families',
'graphics', 'iolib', 'nonparametric', 'qqplot', 'regression', 'robust',
'stats', 'test', 'tools', 'tsa', 'version']
>>> dir(sm.graphics)
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'abline_plot', 'beanplot', 'fboxplot', 'interaction_plot', 'qqplot',
'rainbow', 'rainbowplot', 'violinplot']
>>> dir(sm.tsa)
['AR', 'ARMA', 'DynamicVAR', 'SVAR', 'VAR', '__builtins__', '__doc__',
'__file__', '__name__', '__package__', 'acf', 'acovf', 'add_lag',
'add_trend', 'adfuller', 'ccf', 'ccovf', 'datetools', 'detrend',
'filters', 'grangercausalitytests', 'interp', 'lagmat', 'lagmat2ds',
'pacf', 'pacf_ols', 'pacf_yw', 'periodogram', 'q_stat', 'stattools',
'tsatools', 'var']
```
### Notes
The `api` modules may not include all the public functionality of statsmodels. If you find something that should be added to the api, please file an issue on github or report it to the mailing list.
The subpackages of statsmodels include `api.py` modules that are mainly intended to collect the imports needed for those subpackages. The `subpackage/api.py` files are imported into statsmodels api, for example
```
from .nonparametric import api as nonparametric
```
Users do not need to load the `subpackage/api.py` modules directly.
Direct import for programs
--------------------------
`statsmodels` submodules are arranged by topic (e.g. `discrete` for discrete choice models, or `tsa` for time series analysis). Our directory tree (stripped down) looks something like this:
```
statsmodels/
__init__.py
api.py
discrete/
__init__.py
discrete_model.py
tests/
results/
tsa/
__init__.py
api.py
tsatools.py
stattools.py
arima_model.py
arima_process.py
vector_ar/
__init__.py
var_model.py
tests/
results/
tests/
results/
stats/
__init__.py
api.py
stattools.py
tests/
tools/
__init__.py
tools.py
decorators.py
tests/
```
The submodules that can be import heavy contain an empty `__init__.py`, except for some testing code for running tests for the submodules. The intention is to change all directories to have an `api.py` and empty `__init__.py` in the next release.
### Import examples
Functions and classes:
```
from statsmodels.regression.linear_model import OLS, WLS
from statsmodels.tools.tools import rank, add_constant
```
Modules
```
from statsmodels.datasets import macrodata
import statsmodels.stats import diagnostic
```
Modules with aliases
```
import statsmodels.regression.linear_model as lm
import statsmodels.stats.diagnostic as smsdia
import statsmodels.stats.outliers_influence as oi
```
We do not have currently a convention for aliases of submodules.
statsmodels Sandbox Sandbox
=======
This sandbox contains code that is for various resons not ready to be included in statsmodels proper. It contains modules from the old stats.models code that have not been tested, verified and updated to the new statsmodels structure: cox survival model, mixed effects model with repeated measures, generalized additive model and the formula framework. The sandbox also contains code that is currently being worked on until it fits the pattern of statsmodels or is sufficiently tested.
All sandbox modules have to be explicitly imported to indicate that they are not yet part of the core of statsmodels. The quality and testing of the sandbox code varies widely.
Examples
--------
There are some examples in the `sandbox.examples` folder. Additional examples are directly included in the modules and in subfolders of the sandbox.
Module Reference
----------------
### Time Series analysis `tsa`
In this part we develop models and functions that will be useful for time series analysis. Most of the models and function have been moved to [`statsmodels.tsa`](tsa#module-statsmodels.tsa "statsmodels.tsa: Time-series analysis"). Currently, GARCH models remain in development stage in `sandbox.tsa`.
#### Moving Window Statistics
Most moving window statistics, like rolling mean, moments (up to 4th order), min, max, mean, and variance, are covered by the functions for [Moving (rolling) statistics/moments](http://pandas.pydata.org/pandas-docs/stable/computation.html#moving-rolling-statistics-moments) in Pandas.
| | |
| --- | --- |
| [`movstat.movorder`](generated/statsmodels.sandbox.tsa.movstat.movorder#statsmodels.sandbox.tsa.movstat.movorder "statsmodels.sandbox.tsa.movstat.movorder")(x[, order, windsize, lag]) | moving order statistics |
| [`movstat.movmean`](generated/statsmodels.sandbox.tsa.movstat.movmean#statsmodels.sandbox.tsa.movstat.movmean "statsmodels.sandbox.tsa.movstat.movmean")(x[, windowsize, lag]) | moving window mean |
| [`movstat.movvar`](generated/statsmodels.sandbox.tsa.movstat.movvar#statsmodels.sandbox.tsa.movstat.movvar "statsmodels.sandbox.tsa.movstat.movvar")(x[, windowsize, lag]) | moving window variance |
| [`movstat.movmoment`](generated/statsmodels.sandbox.tsa.movstat.movmoment#statsmodels.sandbox.tsa.movstat.movmoment "statsmodels.sandbox.tsa.movstat.movmoment")(x, k[, windowsize, lag]) | non-central moment |
### Regression and ANOVA
The following two ANOVA functions are fully tested against the NIST test data for balanced one-way ANOVA. `anova_oneway` follows the same pattern as the oneway anova function in scipy.stats but with higher precision for badly scaled problems. `anova_ols` produces the same results as the one way anova however using the OLS model class. It also verifies against the NIST tests, with some problems in the worst scaled cases. It shows how to do simple ANOVA using statsmodels in three lines and is also best taken as a recipe.
| | |
| --- | --- |
| [`anova_oneway`](generated/statsmodels.sandbox.regression.anova_nistcertified.anova_oneway#statsmodels.sandbox.regression.anova_nistcertified.anova_oneway "statsmodels.sandbox.regression.anova_nistcertified.anova_oneway")(y, x[, seq]) | |
| [`anova_ols`](generated/statsmodels.sandbox.regression.anova_nistcertified.anova_ols#statsmodels.sandbox.regression.anova_nistcertified.anova_ols "statsmodels.sandbox.regression.anova_nistcertified.anova_ols")(y, x) | |
The following are helper functions for working with dummy variables and generating ANOVA results with OLS. They are best considered as recipes since they were written with a specific use in mind. These function will eventually be rewritten or reorganized.
| | |
| --- | --- |
| [`try_ols_anova.data2dummy`](generated/statsmodels.sandbox.regression.try_ols_anova.data2dummy#statsmodels.sandbox.regression.try_ols_anova.data2dummy "statsmodels.sandbox.regression.try_ols_anova.data2dummy")(x[, returnall]) | convert array of categories to dummy variables by default drops dummy variable for last category uses ravel, 1d only |
| [`try_ols_anova.data2groupcont`](generated/statsmodels.sandbox.regression.try_ols_anova.data2groupcont#statsmodels.sandbox.regression.try_ols_anova.data2groupcont "statsmodels.sandbox.regression.try_ols_anova.data2groupcont")(x1, x2) | create dummy continuous variable |
| [`try_ols_anova.data2proddummy`](generated/statsmodels.sandbox.regression.try_ols_anova.data2proddummy#statsmodels.sandbox.regression.try_ols_anova.data2proddummy "statsmodels.sandbox.regression.try_ols_anova.data2proddummy")(x) | creates product dummy variables from 2 columns of 2d array |
| [`try_ols_anova.dropname`](generated/statsmodels.sandbox.regression.try_ols_anova.dropname#statsmodels.sandbox.regression.try_ols_anova.dropname "statsmodels.sandbox.regression.try_ols_anova.dropname")(ss, li) | drop names from a list of strings, names to drop are in space delimeted list does not change original list |
| [`try_ols_anova.form2design`](generated/statsmodels.sandbox.regression.try_ols_anova.form2design#statsmodels.sandbox.regression.try_ols_anova.form2design "statsmodels.sandbox.regression.try_ols_anova.form2design")(ss, data) | convert string formula to data dictionary |
The following are helper functions for group statistics where groups are defined by a label array. The qualifying comments for the previous group apply also to this group of functions.
| | |
| --- | --- |
| [`try_catdata.cat2dummy`](generated/statsmodels.sandbox.regression.try_catdata.cat2dummy#statsmodels.sandbox.regression.try_catdata.cat2dummy "statsmodels.sandbox.regression.try_catdata.cat2dummy")(y[, nonseq]) | |
| [`try_catdata.convertlabels`](generated/statsmodels.sandbox.regression.try_catdata.convertlabels#statsmodels.sandbox.regression.try_catdata.convertlabels "statsmodels.sandbox.regression.try_catdata.convertlabels")(ys[, indices]) | convert labels based on multiple variables or string labels to unique index labels 0,1,2,β¦,nk-1 where nk is the number of distinct labels |
| [`try_catdata.groupsstats_1d`](generated/statsmodels.sandbox.regression.try_catdata.groupsstats_1d#statsmodels.sandbox.regression.try_catdata.groupsstats_1d "statsmodels.sandbox.regression.try_catdata.groupsstats_1d")(y, x, labelsunique) | use ndimage to get fast mean and variance |
| [`try_catdata.groupsstats_dummy`](generated/statsmodels.sandbox.regression.try_catdata.groupsstats_dummy#statsmodels.sandbox.regression.try_catdata.groupsstats_dummy "statsmodels.sandbox.regression.try_catdata.groupsstats_dummy")(y, x[, nonseq]) | |
| [`try_catdata.groupstatsbin`](generated/statsmodels.sandbox.regression.try_catdata.groupstatsbin#statsmodels.sandbox.regression.try_catdata.groupstatsbin "statsmodels.sandbox.regression.try_catdata.groupstatsbin")(factors, values) | uses np.bincount, assumes factors/labels are integers |
| [`try_catdata.labelmeanfilter`](generated/statsmodels.sandbox.regression.try_catdata.labelmeanfilter#statsmodels.sandbox.regression.try_catdata.labelmeanfilter "statsmodels.sandbox.regression.try_catdata.labelmeanfilter")(y, x) | |
| [`try_catdata.labelmeanfilter_nd`](generated/statsmodels.sandbox.regression.try_catdata.labelmeanfilter_nd#statsmodels.sandbox.regression.try_catdata.labelmeanfilter_nd "statsmodels.sandbox.regression.try_catdata.labelmeanfilter_nd")(y, x) | |
| [`try_catdata.labelmeanfilter_str`](generated/statsmodels.sandbox.regression.try_catdata.labelmeanfilter_str#statsmodels.sandbox.regression.try_catdata.labelmeanfilter_str "statsmodels.sandbox.regression.try_catdata.labelmeanfilter_str")(ys, x) | |
Additional to these functions, sandbox regression still contains several examples, that are illustrative of the use of the regression models of statsmodels.
### Systems of Regression Equations and Simultaneous Equations
The following are for fitting systems of equations models. Though the returned parameters have been verified as accurate, this code is still very experimental, and the usage of the models will very likely change significantly before they are added to the main codebase.
| | |
| --- | --- |
| [`SUR`](generated/statsmodels.sandbox.sysreg.sur#statsmodels.sandbox.sysreg.SUR "statsmodels.sandbox.sysreg.SUR")(sys[, sigma, dfk]) | Seemingly Unrelated Regression |
| [`Sem2SLS`](generated/statsmodels.sandbox.sysreg.sem2sls#statsmodels.sandbox.sysreg.Sem2SLS "statsmodels.sandbox.sysreg.Sem2SLS")(sys[, indep\_endog, instruments]) | Two-Stage Least Squares for Simultaneous equations |
### Miscellaneous
#### Descriptive Statistics Printing
| | |
| --- | --- |
| [`descstats.sign_test`](generated/statsmodels.sandbox.descstats.sign_test#statsmodels.sandbox.descstats.sign_test "statsmodels.sandbox.descstats.sign_test")(samp[, mu0]) | Signs test. |
| [`descstats.descstats`](generated/statsmodels.sandbox.descstats.descstats#statsmodels.sandbox.descstats.descstats "statsmodels.sandbox.descstats.descstats")(data[, cols, axis]) | Prints descriptive statistics for one or multiple variables. |
### Original stats.models
None of these are fully working. The formula framework is used by cox and mixed.
**Mixed Effects Model with Repeated Measures using an EM Algorithm**
`statsmodels.sandbox.mixed`
**Cox Proportional Hazards Model**
`statsmodels.sandbox.cox`
**Generalized Additive Models**
`statsmodels.sandbox.gam`
**Formula**
`statsmodels.sandbox.formula`
statsmodels Regression with Discrete Dependent Variable Regression with Discrete Dependent Variable
===========================================
Regression models for limited and qualitative dependent variables. The module currently allows the estimation of models with binary (Logit, Probit), nominal (MNLogit), or count (Poisson, NegativeBinomial) data.
Starting with version 0.9, this also includes new count models, that are still experimental in 0.9, NegativeBinomialP, GeneralizedPoisson and zero-inflated models, ZeroInflatedPoisson, ZeroInflatedNegativeBinomialP and ZeroInflatedGeneralizedPoisson.
See [Module Reference](#module-reference) for commands and arguments.
Examples
--------
```
# Load the data from Spector and Mazzeo (1980)
In [1]: spector_data = sm.datasets.spector.load()
In [2]: spector_data.exog = sm.add_constant(spector_data.exog)
# Logit Model
In [3]: logit_mod = sm.Logit(spector_data.endog, spector_data.exog)
In [4]: logit_res = logit_mod.fit()
Optimization terminated successfully.
Current function value: 0.402801
Iterations 7
In [5]: print(logit_res.summary())
```
statsmodels Tools Tools
=====
Our tool collection contains some convenience functions for users and functions that were written mainly for internal use.
Additional to this tools directory, several other subpackages have their own tools modules, for example `statsmodels.tsa.tsatools`
Module Reference
----------------
### Basic tools `tools`
These are basic and miscellaneous tools. The full import path is `statsmodels.tools.tools`.
| | |
| --- | --- |
| [`tools.add_constant`](generated/statsmodels.tools.tools.add_constant#statsmodels.tools.tools.add_constant "statsmodels.tools.tools.add_constant")(data[, prepend, has\_constant]) | Adds a column of ones to an array |
The next group are mostly helper functions that are not separately tested or insufficiently tested.
| | |
| --- | --- |
| [`tools.categorical`](generated/statsmodels.tools.tools.categorical#statsmodels.tools.tools.categorical "statsmodels.tools.tools.categorical")(data[, col, dictnames, drop]) | Returns a dummy matrix given an array of categorical variables. |
| [`tools.clean0`](generated/statsmodels.tools.tools.clean0#statsmodels.tools.tools.clean0 "statsmodels.tools.tools.clean0")(matrix) | Erase columns of zeros: can save some time in pseudoinverse. |
| [`tools.fullrank`](generated/statsmodels.tools.tools.fullrank#statsmodels.tools.tools.fullrank "statsmodels.tools.tools.fullrank")(X[, r]) | Return a matrix whose column span is the same as X. |
| [`tools.isestimable`](generated/statsmodels.tools.tools.isestimable#statsmodels.tools.tools.isestimable "statsmodels.tools.tools.isestimable")(C, D) | True if (Q, P) contrast `C` is estimable for (N, P) design `D` |
| [`tools.recipr`](generated/statsmodels.tools.tools.recipr#statsmodels.tools.tools.recipr "statsmodels.tools.tools.recipr")(x) | Return the reciprocal of an array, setting all entries less than or equal to 0 to 0. |
| [`tools.recipr0`](generated/statsmodels.tools.tools.recipr0#statsmodels.tools.tools.recipr0 "statsmodels.tools.tools.recipr0")(x) | Return the reciprocal of an array, setting all entries equal to 0 as 0. |
| [`tools.unsqueeze`](generated/statsmodels.tools.tools.unsqueeze#statsmodels.tools.tools.unsqueeze "statsmodels.tools.tools.unsqueeze")(data, axis, oldshape) | Unsqueeze a collapsed array |
### Numerical Differentiation
| | |
| --- | --- |
| [`numdiff.approx_fprime`](generated/statsmodels.tools.numdiff.approx_fprime#statsmodels.tools.numdiff.approx_fprime "statsmodels.tools.numdiff.approx_fprime")(x, f[, epsilon, args, β¦]) | Gradient of function, or Jacobian if function f returns 1d array |
| [`numdiff.approx_fprime_cs`](generated/statsmodels.tools.numdiff.approx_fprime_cs#statsmodels.tools.numdiff.approx_fprime_cs "statsmodels.tools.numdiff.approx_fprime_cs")(x, f[, epsilon, β¦]) | Calculate gradient or Jacobian with complex step derivative approximation |
| [`numdiff.approx_hess1`](generated/statsmodels.tools.numdiff.approx_hess1#statsmodels.tools.numdiff.approx_hess1 "statsmodels.tools.numdiff.approx_hess1")(x, f[, epsilon, args, β¦]) | Calculate Hessian with finite difference derivative approximation |
| [`numdiff.approx_hess2`](generated/statsmodels.tools.numdiff.approx_hess2#statsmodels.tools.numdiff.approx_hess2 "statsmodels.tools.numdiff.approx_hess2")(x, f[, epsilon, args, β¦]) | Calculate Hessian with finite difference derivative approximation |
| [`numdiff.approx_hess3`](generated/statsmodels.tools.numdiff.approx_hess3#statsmodels.tools.numdiff.approx_hess3 "statsmodels.tools.numdiff.approx_hess3")(x, f[, epsilon, args, β¦]) | Calculate Hessian with finite difference derivative approximation |
| [`numdiff.approx_hess_cs`](generated/statsmodels.tools.numdiff.approx_hess_cs#statsmodels.tools.numdiff.approx_hess_cs "statsmodels.tools.numdiff.approx_hess_cs")(x, f[, epsilon, β¦]) | Calculate Hessian with complex-step derivative approximation Calculate Hessian with finite difference derivative approximation |
### Measure for fit performance `eval_measures`
The first group of function in this module are standalone versions of information criteria, aic bic and hqic. The function with `_sigma` suffix take the error sum of squares as argument, those without, take the value of the log-likelihood, `llf`, as argument.
The second group of function are measures of fit or prediction performance, which are mostly one liners to be used as helper functions. All of those calculate a performance or distance statistic for the difference between two arrays. For example in the case of Monte Carlo or cross-validation, the first array would be the estimation results for the different replications or draws, while the second array would be the true or observed values.
| | |
| --- | --- |
| [`eval_measures.aic`](generated/statsmodels.tools.eval_measures.aic#statsmodels.tools.eval_measures.aic "statsmodels.tools.eval_measures.aic")(llf, nobs, df\_modelwc) | Akaike information criterion |
| [`eval_measures.aic_sigma`](generated/statsmodels.tools.eval_measures.aic_sigma#statsmodels.tools.eval_measures.aic_sigma "statsmodels.tools.eval_measures.aic_sigma")(sigma2, nobs, df\_modelwc) | Akaike information criterion |
| [`eval_measures.aicc`](generated/statsmodels.tools.eval_measures.aicc#statsmodels.tools.eval_measures.aicc "statsmodels.tools.eval_measures.aicc")(llf, nobs, df\_modelwc) | Akaike information criterion (AIC) with small sample correction |
| [`eval_measures.aicc_sigma`](generated/statsmodels.tools.eval_measures.aicc_sigma#statsmodels.tools.eval_measures.aicc_sigma "statsmodels.tools.eval_measures.aicc_sigma")(sigma2, nobs, β¦) | Akaike information criterion (AIC) with small sample correction |
| [`eval_measures.bic`](generated/statsmodels.tools.eval_measures.bic#statsmodels.tools.eval_measures.bic "statsmodels.tools.eval_measures.bic")(llf, nobs, df\_modelwc) | Bayesian information criterion (BIC) or Schwarz criterion |
| [`eval_measures.bic_sigma`](generated/statsmodels.tools.eval_measures.bic_sigma#statsmodels.tools.eval_measures.bic_sigma "statsmodels.tools.eval_measures.bic_sigma")(sigma2, nobs, df\_modelwc) | Bayesian information criterion (BIC) or Schwarz criterion |
| [`eval_measures.hqic`](generated/statsmodels.tools.eval_measures.hqic#statsmodels.tools.eval_measures.hqic "statsmodels.tools.eval_measures.hqic")(llf, nobs, df\_modelwc) | Hannan-Quinn information criterion (HQC) |
| [`eval_measures.hqic_sigma`](generated/statsmodels.tools.eval_measures.hqic_sigma#statsmodels.tools.eval_measures.hqic_sigma "statsmodels.tools.eval_measures.hqic_sigma")(sigma2, nobs, β¦) | Hannan-Quinn information criterion (HQC) |
| [`eval_measures.bias`](generated/statsmodels.tools.eval_measures.bias#statsmodels.tools.eval_measures.bias "statsmodels.tools.eval_measures.bias")(x1, x2[, axis]) | bias, mean error |
| [`eval_measures.iqr`](generated/statsmodels.tools.eval_measures.iqr#statsmodels.tools.eval_measures.iqr "statsmodels.tools.eval_measures.iqr")(x1, x2[, axis]) | interquartile range of error |
| [`eval_measures.maxabs`](generated/statsmodels.tools.eval_measures.maxabs#statsmodels.tools.eval_measures.maxabs "statsmodels.tools.eval_measures.maxabs")(x1, x2[, axis]) | maximum absolute error |
| [`eval_measures.meanabs`](generated/statsmodels.tools.eval_measures.meanabs#statsmodels.tools.eval_measures.meanabs "statsmodels.tools.eval_measures.meanabs")(x1, x2[, axis]) | mean absolute error |
| [`eval_measures.medianabs`](generated/statsmodels.tools.eval_measures.medianabs#statsmodels.tools.eval_measures.medianabs "statsmodels.tools.eval_measures.medianabs")(x1, x2[, axis]) | median absolute error |
| [`eval_measures.medianbias`](generated/statsmodels.tools.eval_measures.medianbias#statsmodels.tools.eval_measures.medianbias "statsmodels.tools.eval_measures.medianbias")(x1, x2[, axis]) | median bias, median error |
| [`eval_measures.mse`](generated/statsmodels.tools.eval_measures.mse#statsmodels.tools.eval_measures.mse "statsmodels.tools.eval_measures.mse")(x1, x2[, axis]) | mean squared error |
| [`eval_measures.rmse`](generated/statsmodels.tools.eval_measures.rmse#statsmodels.tools.eval_measures.rmse "statsmodels.tools.eval_measures.rmse")(x1, x2[, axis]) | root mean squared error |
| [`eval_measures.stde`](generated/statsmodels.tools.eval_measures.stde#statsmodels.tools.eval_measures.stde "statsmodels.tools.eval_measures.stde")(x1, x2[, ddof, axis]) | standard deviation of error |
| [`eval_measures.vare`](generated/statsmodels.tools.eval_measures.vare#statsmodels.tools.eval_measures.vare "statsmodels.tools.eval_measures.vare")(x1, x2[, ddof, axis]) | variance of error |
| programming_docs |
statsmodels Empirical Likelihood emplike Empirical Likelihood emplike
============================
Introduction
------------
Empirical likelihood is a method of nonparametric inference and estimation that lifts the obligation of having to specify a family of underlying distributions. Moreover, empirical likelihood methods do not require re-sampling but still uniquely determine confidence regions whose shape mirrors the shape of the data. In essence, empirical likelihood attempts to combine the benefits of parametric and nonparametric methods while limiting their shortcomings. The main difficulties of empirical likelihood is the computationally intensive methods required to conduct inference. [`statsmodels.emplike`](#module-statsmodels.emplike "statsmodels.emplike: Empirical likelihood tools") attempts to provide a user-friendly interface that allows the end user to effectively conduct empirical likelihood analysis without having to concern themselves with the computational burdens.
Currently, `emplike` provides methods to conduct hypothesis tests and form confidence intervals for descriptive statistics. Empirical likelihood estimation and inference in a regression, accelerated failure time and instrumental variable model are currently under development.
### References
The main reference for empirical likelihood is:
```
Owen, A.B. "Empirical Likelihood." Chapman and Hall, 2001.
```
Examples
--------
```
In [1]: import numpy as np
In [2]: import statsmodels.api as sm
# Generate Data
In [3]: x = np.random.standard_normal(50)
# initiate EL
In [4]: el = sm.emplike.DescStat(x)
# confidence interval for the mean
In [5]: el.ci_mean()
Out[5]: (-0.5155986884515734, 0.08136630955859389)
# test variance is 1
In [6]: el.test_var(1)
```
statsmodels Multiple Imputation with Chained Equations Multiple Imputation with Chained Equations
==========================================
The MICE module allows most Statsmodels models to be fit to a dataset with missing values on the independent and/or dependent variables, and provides rigorous standard errors for the fitted parameters. The basic idea is to treat each variable with missing values as the dependent variable in a regression, with some or all of the remaining variables as its predictors. The MICE procedure cycles through these models, fitting each in turn, then uses a procedure called βpredictive mean matchingβ (PMM) to generate random draws from the predictive distributions determined by the fitted models. These random draws become the imputed values for one imputed data set.
By default, each variable with missing variables is modeled using a linear regression with main effects for all other variables in the data set. Note that even when the imputation model is linear, the PMM procedure preserves the domain of each variable. Thus, for example, if all observed values for a given variable are positive, all imputed values for the variable will always be positive. The user also has the option to specify which model is used to produce imputed values for each variable.
Classes
-------
| | |
| --- | --- |
| [`MICE`](generated/statsmodels.imputation.mice.mice#statsmodels.imputation.mice.MICE "statsmodels.imputation.mice.MICE")(model\_formula, model\_class, data[, β¦]) | Multiple Imputation with Chained Equations. |
| [`MICEData`](generated/statsmodels.imputation.mice.micedata#statsmodels.imputation.mice.MICEData "statsmodels.imputation.mice.MICEData")(data[, perturbation\_method, k\_pmm, β¦]) | Wrap a data set to allow missing data handling with MICE. |
Implementation Details
----------------------
Internally, this function uses [pandas.isnull](http://pandas.pydata.org/pandas-docs/stable/missing_data.html#working-with-missing-data). Anything that returns True from this function will be treated as missing data.
statsmodels Pitfalls Pitfalls
========
This page lists issues which may arise while using statsmodels. These can be the result of data-related or statistical problems, software design, βnon-standardβ use of models, or edge cases.
statsmodels provides several warnings and helper functions for diagnostic checking (see this [blog article](http://jpktd.blogspot.ca/2012/01/anscombe-and-diagnostic-statistics.html) for an example of misspecification checks in linear regression). The coverage is of course not comprehensive, but more warnings and diagnostic functions will be added over time.
While the underlying statistical problems are the same for all statistical packages, software implementations differ in the way extreme or corner cases are handled. Please report corner cases for which the models might not work, so we can treat them appropriately.
Repeated calls to fit with different parameters
-----------------------------------------------
Result instances often need to access attributes from the corresponding model instance. Fitting a model multiple times with different arguments can change model attributes. This means that the result instance may no longer point to the correct model attributes after the model has been re-fit.
It is therefore best practice to create separate model instances when we want to fit a model using different fit function arguments.
For example, this works without problem because we are not keeping the results instance for further use
```
mod = AR(endog)
aic = []
for lag in range(1,11):
res = mod.fit(maxlag=lag)
aic.append(res.aic)
```
However, when we want to hold on to two different estimation results, then it is recommended to create two separate model instances.
```
mod1 = RLM(endog, exog)
res1 = mod1.fit(scale_est='mad')
mod2 = RLM(endog, exog)
res2 = mod2.fit(scale_est=sm.robust.scale.HuberScale())
```
Unidentified Parameters
-----------------------
### Rank deficient exog, perfect multicollinearity
Models based on linear models, GLS, RLM, GLM and similar, use a generalized inverse. This means that:
* Rank deficient matrices will not raise an error
* Cases of almost perfect multicollinearity or ill-conditioned design matrices might produce numerically unstable results. Users need to manually check the rank or condition number of the matrix if this is not the desired behavior
Note: Statsmodels currently fails on the NIST benchmark case for Filip if the data is not rescaled, see [this blog](http://jpktd.blogspot.ca/2012/03/numerical-accuracy-in-linear-least.html)
### Incomplete convergence in maximum likelihood estimation
In some cases, the maximum likelihood estimator might not exist, parameters might be infinite or not unique (e.g. (quasi-)separation in models with binary endogenous variable). Under the default settings, statsmodels will print a warning if the optimization algorithm stops without reaching convergence. However, it is important to know that the convergence criteria may sometimes falsely indicate convergence (e.g. if the value of the objective function converged but not the parameters). In general, a user needs to verify convergence.
For binary Logit and Probit models, statsmodels raises an exception if perfect prediction is detected. There is, however, no check for quasi-perfect prediction.
Other Problems
--------------
### Insufficient variation in the data
It is possible that there is insufficient variation in the data for small datasets or for data with small groups in categorical variables. In these cases, the results might not be identified or some hidden problems might occur.
The only currently known case is a perfect fit in robust linear model estimation. For RLM, if residuals are equal to zero, then it does not cause an exception, but having this perfect fit can produce NaNs in some results (scale=0 and 0/0 division) (issue #55).
statsmodels Weight Functions Weight Functions
================
Andrewβs Wave
Hampel 17A
Huberβs t
Least Squares
Ramsayβs Ea
Trimmed Mean
Tukeyβs Biweight
statsmodels Linear Regression Linear Regression
=================
Linear models with independently and identically distributed errors, and for errors with heteroscedasticity or autocorrelation. This module allows estimation by ordinary least squares (OLS), weighted least squares (WLS), generalized least squares (GLS), and feasible generalized least squares with autocorrelated AR(p) errors.
See [Module Reference](#module-reference) for commands and arguments.
Examples
--------
```
# Load modules and data
In [1]: import numpy as np
In [2]: import statsmodels.api as sm
In [3]: spector_data = sm.datasets.spector.load()
In [4]: spector_data.exog = sm.add_constant(spector_data.exog, prepend=False)
# Fit and summarize OLS model
In [5]: mod = sm.OLS(spector_data.endog, spector_data.exog)
In [6]: res = mod.fit()
In [7]: print(res.summary())
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.416
Model: OLS Adj. R-squared: 0.353
Method: Least Squares F-statistic: 6.646
Date: Mon, 14 May 2018 Prob (F-statistic): 0.00157
Time: 21:48:12 Log-Likelihood: -12.978
No. Observations: 32 AIC: 33.96
Df Residuals: 28 BIC: 39.82
Df Model: 3
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
x1 0.4639 0.162 2.864 0.008 0.132 0.796
x2 0.0105 0.019 0.539 0.594 -0.029 0.050
x3 0.3786 0.139 2.720 0.011 0.093 0.664
const -1.4980 0.524 -2.859 0.008 -2.571 -0.425
==============================================================================
Omnibus: 0.176 Durbin-Watson: 2.346
Prob(Omnibus): 0.916 Jarque-Bera (JB): 0.167
Skew: 0.141 Prob(JB): 0.920
Kurtosis: 2.786 Cond. No. 176.
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
Detailed examples can be found here:
* [OLS](examples/notebooks/generated/ols)
* [WLS](examples/notebooks/generated/wls)
* [GLS](examples/notebooks/generated/gls)
* [Recursive LS](examples/notebooks/generated/recursive_ls)
Technical Documentation
-----------------------
The statistical model is assumed to be
\(Y = X\beta + \mu\), where \(\mu\sim N\left(0,\Sigma\right).\) Depending on the properties of \(\Sigma\), we have currently four classes available:
* GLS : generalized least squares for arbitrary covariance \(\Sigma\)
* OLS : ordinary least squares for i.i.d. errors \(\Sigma=\textbf{I}\)
* WLS : weighted least squares for heteroskedastic errors \(\text{diag}\left (\Sigma\right)\)
* GLSAR : feasible generalized least squares with autocorrelated AR(p) errors \(\Sigma=\Sigma\left(\rho\right)\)
All regression models define the same methods and follow the same structure, and can be used in a similar fashion. Some of them contain additional model specific methods and attributes.
GLS is the superclass of the other regression classes except for RecursiveLS.
### References
General reference for regression models:
* D.C. Montgomery and E.A. Peck. βIntroduction to Linear Regression Analysis.β 2nd. Ed., Wiley, 1992.
Econometrics references for regression models:
* R.Davidson and J.G. MacKinnon. βEconometric Theory and Methods,β Oxford, 2004.
* W.Green. βEconometric Analysis,β 5th ed., Pearson, 2003.
### Attributes
The following is more verbose description of the attributes which is mostly common to all regression classes
`pinv_wexog : array` The `p` x `n` Moore-Penrose pseudoinverse of the whitened design matrix. It is approximately equal to \(\left(X^{T}\Sigma^{-1}X\right)^{-1}X^{T}\Psi\), where \(\Psi\) is defined such that \(\Psi\Psi^{T}=\Sigma^{-1}\).
`cholsimgainv : array` The `n` x `n` upper triangular matrix \(\Psi^{T}\) that satisfies \(\Psi\Psi^{T}=\Sigma^{-1}\).
`df_model : float` The model degrees of freedom. This is equal to `p` - 1, where `p` is the number of regressors. Note that the intercept is not counted as using a degree of freedom here.
`df_resid : float` The residual degrees of freedom. This is equal `n - p` where `n` is the number of observations and `p` is the number of parameters. Note that the intercept is counted as using a degree of freedom here.
`llf : float` The value of the likelihood function of the fitted model.
`nobs : float` The number of observations `n`
`normalized_cov_params : array` A `p` x `p` array equal to \((X^{T}\Sigma^{-1}X)^{-1}\).
`sigma : array` The `n` x `n` covariance matrix of the error terms: \(\mu\sim N\left(0,\Sigma\right)\).
`wexog : array` The whitened design matrix \(\Psi^{T}X\).
`wendog : array` The whitened response variable \(\Psi^{T}Y\). Module Reference
----------------
### Model Classes
| | |
| --- | --- |
| [`OLS`](generated/statsmodels.regression.linear_model.ols#statsmodels.regression.linear_model.OLS "statsmodels.regression.linear_model.OLS")(endog[, exog, missing, hasconst]) | A simple ordinary least squares model. |
| [`GLS`](generated/statsmodels.regression.linear_model.gls#statsmodels.regression.linear_model.GLS "statsmodels.regression.linear_model.GLS")(endog, exog[, sigma, missing, hasconst]) | Generalized least squares model with a general covariance structure. |
| [`WLS`](generated/statsmodels.regression.linear_model.wls#statsmodels.regression.linear_model.WLS "statsmodels.regression.linear_model.WLS")(endog, exog[, weights, missing, hasconst]) | A regression model with diagonal but non-identity covariance structure. |
| [`GLSAR`](generated/statsmodels.regression.linear_model.glsar#statsmodels.regression.linear_model.GLSAR "statsmodels.regression.linear_model.GLSAR")(endog[, exog, rho, missing]) | A regression model with an AR(p) covariance structure. |
| [`yule_walker`](generated/statsmodels.regression.linear_model.yule_walker#statsmodels.regression.linear_model.yule_walker "statsmodels.regression.linear_model.yule_walker")(X[, order, method, df, inv, demean]) | Estimate AR(p) parameters from a sequence X using Yule-Walker equation. |
| | |
| --- | --- |
| [`QuantReg`](generated/statsmodels.regression.quantile_regression.quantreg#statsmodels.regression.quantile_regression.QuantReg "statsmodels.regression.quantile_regression.QuantReg")(endog, exog, \*\*kwargs) | Quantile Regression |
| | |
| --- | --- |
| [`RecursiveLS`](generated/statsmodels.regression.recursive_ls.recursivels#statsmodels.regression.recursive_ls.RecursiveLS "statsmodels.regression.recursive_ls.RecursiveLS")(endog, exog, \*\*kwargs) | Recursive least squares |
### Results Classes
Fitting a linear regression model returns a results class. OLS has a specific results class with some additional methods compared to the results class of the other linear models.
| | |
| --- | --- |
| [`RegressionResults`](generated/statsmodels.regression.linear_model.regressionresults#statsmodels.regression.linear_model.RegressionResults "statsmodels.regression.linear_model.RegressionResults")(model, params[, β¦]) | This class summarizes the fit of a linear regression model. |
| [`OLSResults`](generated/statsmodels.regression.linear_model.olsresults#statsmodels.regression.linear_model.OLSResults "statsmodels.regression.linear_model.OLSResults")(model, params[, β¦]) | Results class for for an OLS model. |
| [`PredictionResults`](generated/statsmodels.regression.linear_model.predictionresults#statsmodels.regression.linear_model.PredictionResults "statsmodels.regression.linear_model.PredictionResults")(predicted\_mean, β¦[, df, β¦]) | |
| | |
| --- | --- |
| [`QuantRegResults`](generated/statsmodels.regression.quantile_regression.quantregresults#statsmodels.regression.quantile_regression.QuantRegResults "statsmodels.regression.quantile_regression.QuantRegResults")(model, params[, β¦]) | Results instance for the QuantReg model |
| | |
| --- | --- |
| [`RecursiveLSResults`](generated/statsmodels.regression.recursive_ls.recursivelsresults#statsmodels.regression.recursive_ls.RecursiveLSResults "statsmodels.regression.recursive_ls.RecursiveLSResults")(model, params, filter\_results) | Class to hold results from fitting a recursive least squares model. |
statsmodels Frequently Asked Question Frequently Asked Question
=========================
What do endog and exog mean?
----------------------------
These are shorthand for endogenous and exogenous variables. You might be more comfortable with the common `y` and `X` notation in linear models. Sometimes the endogenous variable `y` is called a dependent variable. Likewise, sometimes the exogenous variables `X` are called the independent variables. You can read about this in greater detail at [endog, exog, whatβs that?](endog_exog#endog-exog)
How does statsmodels handle missing data?
-----------------------------------------
Missing data can be handled via the `missing` keyword argument. Every model takes this keyword. You can find more information in the docstring of [`statsmodels.base.Model`](http://www.statsmodels.org/stable/dev/generated/statsmodels.base.model.Model.html#statsmodels.base.model.Model "statsmodels.base.model.Model").
Why wonβt statsmodels build?
----------------------------
If youβre on Python 3.4, you *must* use Cython 0.20.1. If youβre still having problems, try running
```
python setup.py clean
```
What if my question isnβt answered here?
----------------------------------------
You may find answers for questions that have not yet been added here on GitHub under the [FAQ issues tag](https://github.com/statsmodels/statsmodels/labels/FAQ). If not, please ask your question on stackoverflow using the [statsmodels tag](https://stackoverflow.com/questions/tagged/statsmodels) or on the [mailing list](https://groups.google.com/forum/#!forum/pystatsmodels).
statsmodels Robust Linear Models Robust Linear Models
====================
Robust linear models with support for the M-estimators listed under [Norms](#norms).
See [Module Reference](#module-reference) for commands and arguments.
Examples
--------
```
# Load modules and data
In [1]: import statsmodels.api as sm
In [2]: data = sm.datasets.stackloss.load()
In [3]: data.exog = sm.add_constant(data.exog)
# Fit model and print summary
In [4]: rlm_model = sm.RLM(data.endog, data.exog, M=sm.robust.norms.HuberT())
In [5]: rlm_results = rlm_model.fit()
In [6]: print(rlm_results.params)
[-41.0265 0.8294 0.9261 -0.1278]
```
Detailed examples can be found here:
* [Robust Models 1](examples/notebooks/generated/robust_models_0)
* [Robust Models 2](examples/notebooks/generated/robust_models_1)
Technical Documentation
-----------------------
* [Weight Functions](rlm_techn1)
### References
* PJ Huber. βRobust Statisticsβ John Wiley and Sons, Inc., New York. 1981.
* PJ Huber. 1973, βThe 1972 Wald Memorial Lectures: Robust Regression: Asymptotics, Conjectures, and Monte Carlo.β The Annals of Statistics, 1.5, 799-821.
* R Venables, B Ripley. βModern Applied Statistics in Sβ Springer, New York,
Module Reference
----------------
### Model Classes
| | |
| --- | --- |
| [`RLM`](generated/statsmodels.robust.robust_linear_model.rlm#statsmodels.robust.robust_linear_model.RLM "statsmodels.robust.robust_linear_model.RLM")(endog, exog[, M, missing]) | Robust Linear Models |
### Model Results
| | |
| --- | --- |
| [`RLMResults`](generated/statsmodels.robust.robust_linear_model.rlmresults#statsmodels.robust.robust_linear_model.RLMResults "statsmodels.robust.robust_linear_model.RLMResults")(model, params, β¦) | Class to contain RLM results |
### Norms
| | |
| --- | --- |
| [`AndrewWave`](generated/statsmodels.robust.norms.andrewwave#statsmodels.robust.norms.AndrewWave "statsmodels.robust.norms.AndrewWave")([a]) | Andrewβs wave for M estimation. |
| [`Hampel`](generated/statsmodels.robust.norms.hampel#statsmodels.robust.norms.Hampel "statsmodels.robust.norms.Hampel")([a, b, c]) | Hampel function for M-estimation. |
| [`HuberT`](generated/statsmodels.robust.norms.hubert#statsmodels.robust.norms.HuberT "statsmodels.robust.norms.HuberT")([t]) | Huberβs T for M estimation. |
| [`LeastSquares`](generated/statsmodels.robust.norms.leastsquares#statsmodels.robust.norms.LeastSquares "statsmodels.robust.norms.LeastSquares") | Least squares rho for M-estimation and its derived functions. |
| [`RamsayE`](generated/statsmodels.robust.norms.ramsaye#statsmodels.robust.norms.RamsayE "statsmodels.robust.norms.RamsayE")([a]) | Ramsayβs Ea for M estimation. |
| [`RobustNorm`](generated/statsmodels.robust.norms.robustnorm#statsmodels.robust.norms.RobustNorm "statsmodels.robust.norms.RobustNorm") | The parent class for the norms used for robust regression. |
| [`TrimmedMean`](generated/statsmodels.robust.norms.trimmedmean#statsmodels.robust.norms.TrimmedMean "statsmodels.robust.norms.TrimmedMean")([c]) | Trimmed mean function for M-estimation. |
| [`TukeyBiweight`](generated/statsmodels.robust.norms.tukeybiweight#statsmodels.robust.norms.TukeyBiweight "statsmodels.robust.norms.TukeyBiweight")([c]) | Tukeyβs biweight function for M-estimation. |
| [`estimate_location`](generated/statsmodels.robust.norms.estimate_location#statsmodels.robust.norms.estimate_location "statsmodels.robust.norms.estimate_location")(a, scale[, norm, axis, β¦]) | M-estimator of location using self.norm and a current estimator of scale. |
### Scale
| | |
| --- | --- |
| [`Huber`](generated/statsmodels.robust.scale.huber#statsmodels.robust.scale.Huber "statsmodels.robust.scale.Huber")([c, tol, maxiter, norm]) | Huberβs proposal 2 for estimating location and scale jointly. |
| [`HuberScale`](generated/statsmodels.robust.scale.huberscale#statsmodels.robust.scale.HuberScale "statsmodels.robust.scale.HuberScale")([d, tol, maxiter]) | Huberβs scaling for fitting robust linear models. |
| [`mad`](generated/statsmodels.robust.scale.mad#statsmodels.robust.scale.mad "statsmodels.robust.scale.mad")(a[, c, axis, center]) | The Median Absolute Deviation along given axis of an array |
| [`hubers_scale`](generated/statsmodels.robust.scale.hubers_scale#statsmodels.robust.scale.hubers_scale "statsmodels.robust.scale.hubers_scale") | Huberβs scaling for fitting robust linear models. |
| programming_docs |
statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.rvs statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.rvs
================================================================
`ExpTransf_gen.rvs(*args, **kwds)`
Random variates of given type.
| Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information).
* **loc** (*array\_like**,* *optional*) β Location parameter (default=0).
* **scale** (*array\_like**,* *optional*) β Scale parameter (default=1).
* **size** (*int* *or* *tuple of ints**,* *optional*) β Defining number of random variates (default is 1).
* **random\_state** (None or int or `np.random.RandomState` instance, optional) β If int or RandomState, use it for drawing the random variates. If None, rely on `self.random_state`. Default is None.
|
| Returns: | **rvs** β Random variates of given `size`. |
| Return type: | ndarray or scalar |
statsmodels statsmodels.duration.hazard_regression.PHRegResults.remove_data statsmodels.duration.hazard\_regression.PHRegResults.remove\_data
=================================================================
`PHRegResults.remove_data()`
remove data arrays, all nobs arrays from result and model
This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.
Warning
Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.
Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.
The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data.
The attributes to remove are named in:
`model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name.
`result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name)
`result._data_attr_model : arrays attached to the model` instance but not to the results instance
statsmodels statsmodels.miscmodels.tmodel.TLinearModel statsmodels.miscmodels.tmodel.TLinearModel
==========================================
`class statsmodels.miscmodels.tmodel.TLinearModel(endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/tmodel.html#TLinearModel)
Maximum Likelihood Estimation of Linear Model with t-distributed errors
This is an example for generic MLE.
Except for defining the negative log-likelihood method, all methods and results are generic. Gradients and Hessian and all resulting statistics are based on numerical differentiation.
#### Methods
| | |
| --- | --- |
| [`expandparams`](statsmodels.miscmodels.tmodel.tlinearmodel.expandparams#statsmodels.miscmodels.tmodel.TLinearModel.expandparams "statsmodels.miscmodels.tmodel.TLinearModel.expandparams")(params) | expand to full parameter array when some parameters are fixed |
| [`fit`](statsmodels.miscmodels.tmodel.tlinearmodel.fit#statsmodels.miscmodels.tmodel.TLinearModel.fit "statsmodels.miscmodels.tmodel.TLinearModel.fit")([start\_params, method, maxiter, β¦]) | Fit the model using maximum likelihood. |
| [`from_formula`](statsmodels.miscmodels.tmodel.tlinearmodel.from_formula#statsmodels.miscmodels.tmodel.TLinearModel.from_formula "statsmodels.miscmodels.tmodel.TLinearModel.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. |
| [`hessian`](statsmodels.miscmodels.tmodel.tlinearmodel.hessian#statsmodels.miscmodels.tmodel.TLinearModel.hessian "statsmodels.miscmodels.tmodel.TLinearModel.hessian")(params) | Hessian of log-likelihood evaluated at params |
| [`hessian_factor`](statsmodels.miscmodels.tmodel.tlinearmodel.hessian_factor#statsmodels.miscmodels.tmodel.TLinearModel.hessian_factor "statsmodels.miscmodels.tmodel.TLinearModel.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian |
| [`information`](statsmodels.miscmodels.tmodel.tlinearmodel.information#statsmodels.miscmodels.tmodel.TLinearModel.information "statsmodels.miscmodels.tmodel.TLinearModel.information")(params) | Fisher information matrix of model |
| [`initialize`](statsmodels.miscmodels.tmodel.tlinearmodel.initialize#statsmodels.miscmodels.tmodel.TLinearModel.initialize "statsmodels.miscmodels.tmodel.TLinearModel.initialize")() | Initialize (possibly re-initialize) a Model instance. |
| [`loglike`](statsmodels.miscmodels.tmodel.tlinearmodel.loglike#statsmodels.miscmodels.tmodel.TLinearModel.loglike "statsmodels.miscmodels.tmodel.TLinearModel.loglike")(params) | Log-likelihood of model. |
| [`loglikeobs`](statsmodels.miscmodels.tmodel.tlinearmodel.loglikeobs#statsmodels.miscmodels.tmodel.TLinearModel.loglikeobs "statsmodels.miscmodels.tmodel.TLinearModel.loglikeobs")(params) | |
| [`nloglike`](statsmodels.miscmodels.tmodel.tlinearmodel.nloglike#statsmodels.miscmodels.tmodel.TLinearModel.nloglike "statsmodels.miscmodels.tmodel.TLinearModel.nloglike")(params) | |
| [`nloglikeobs`](statsmodels.miscmodels.tmodel.tlinearmodel.nloglikeobs#statsmodels.miscmodels.tmodel.TLinearModel.nloglikeobs "statsmodels.miscmodels.tmodel.TLinearModel.nloglikeobs")(params) | Loglikelihood of linear model with t distributed errors. |
| [`predict`](statsmodels.miscmodels.tmodel.tlinearmodel.predict#statsmodels.miscmodels.tmodel.TLinearModel.predict "statsmodels.miscmodels.tmodel.TLinearModel.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. |
| [`reduceparams`](statsmodels.miscmodels.tmodel.tlinearmodel.reduceparams#statsmodels.miscmodels.tmodel.TLinearModel.reduceparams "statsmodels.miscmodels.tmodel.TLinearModel.reduceparams")(params) | |
| [`score`](statsmodels.miscmodels.tmodel.tlinearmodel.score#statsmodels.miscmodels.tmodel.TLinearModel.score "statsmodels.miscmodels.tmodel.TLinearModel.score")(params) | Gradient of log-likelihood evaluated at params |
| [`score_obs`](statsmodels.miscmodels.tmodel.tlinearmodel.score_obs#statsmodels.miscmodels.tmodel.TLinearModel.score_obs "statsmodels.miscmodels.tmodel.TLinearModel.score_obs")(params, \*\*kwds) | Jacobian/Gradient of log-likelihood evaluated at params for each observation. |
#### Attributes
| | |
| --- | --- |
| `endog_names` | Names of endogenous variables |
| `exog_names` | Names of exogenous variables |
statsmodels statsmodels.regression.linear_model.OLSResults.save statsmodels.regression.linear\_model.OLSResults.save
====================================================
`OLSResults.save(fname, remove_data=False)`
save a pickle of this instance
| Parameters: | * **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle.
* **remove\_data** (*bool*) β If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None.
|
#### Notes
If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception.
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.observed_information_matrix statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.observed\_information\_matrix
======================================================================================
`DynamicFactor.observed_information_matrix(params, transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)`
Observed information matrix
| Parameters: | * **params** (*array\_like**,* *optional*) β Array of parameters at which to evaluate the loglikelihood function.
* **\*\*kwargs** β Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details.
|
#### Notes
This method is from Harvey (1989), which shows that the information matrix only depends on terms from the gradient. This implementation is partially analytic and partially numeric approximation, therefore, because it uses the analytic formula for the information matrix, with numerically computed elements of the gradient.
#### References
Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press.
statsmodels statsmodels.discrete.discrete_model.DiscreteModel statsmodels.discrete.discrete\_model.DiscreteModel
==================================================
`class statsmodels.discrete.discrete_model.DiscreteModel(endog, exog, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteModel)
Abstract class for discrete choice models.
This class does not do anything itself but lays out the methods and call signature expected of child classes in addition to those of statsmodels.model.LikelihoodModel.
#### Methods
| | |
| --- | --- |
| [`cdf`](statsmodels.discrete.discrete_model.discretemodel.cdf#statsmodels.discrete.discrete_model.DiscreteModel.cdf "statsmodels.discrete.discrete_model.DiscreteModel.cdf")(X) | The cumulative distribution function of the model. |
| [`cov_params_func_l1`](statsmodels.discrete.discrete_model.discretemodel.cov_params_func_l1#statsmodels.discrete.discrete_model.DiscreteModel.cov_params_func_l1 "statsmodels.discrete.discrete_model.DiscreteModel.cov_params_func_l1")(likelihood\_model, xopt, β¦) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. |
| [`fit`](statsmodels.discrete.discrete_model.discretemodel.fit#statsmodels.discrete.discrete_model.DiscreteModel.fit "statsmodels.discrete.discrete_model.DiscreteModel.fit")([start\_params, method, maxiter, β¦]) | Fit the model using maximum likelihood. |
| [`fit_regularized`](statsmodels.discrete.discrete_model.discretemodel.fit_regularized#statsmodels.discrete.discrete_model.DiscreteModel.fit_regularized "statsmodels.discrete.discrete_model.DiscreteModel.fit_regularized")([start\_params, method, β¦]) | Fit the model using a regularized maximum likelihood. |
| [`from_formula`](statsmodels.discrete.discrete_model.discretemodel.from_formula#statsmodels.discrete.discrete_model.DiscreteModel.from_formula "statsmodels.discrete.discrete_model.DiscreteModel.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. |
| [`hessian`](statsmodels.discrete.discrete_model.discretemodel.hessian#statsmodels.discrete.discrete_model.DiscreteModel.hessian "statsmodels.discrete.discrete_model.DiscreteModel.hessian")(params) | The Hessian matrix of the model |
| [`information`](statsmodels.discrete.discrete_model.discretemodel.information#statsmodels.discrete.discrete_model.DiscreteModel.information "statsmodels.discrete.discrete_model.DiscreteModel.information")(params) | Fisher information matrix of model |
| [`initialize`](statsmodels.discrete.discrete_model.discretemodel.initialize#statsmodels.discrete.discrete_model.DiscreteModel.initialize "statsmodels.discrete.discrete_model.DiscreteModel.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. |
| [`loglike`](statsmodels.discrete.discrete_model.discretemodel.loglike#statsmodels.discrete.discrete_model.DiscreteModel.loglike "statsmodels.discrete.discrete_model.DiscreteModel.loglike")(params) | Log-likelihood of model. |
| [`pdf`](statsmodels.discrete.discrete_model.discretemodel.pdf#statsmodels.discrete.discrete_model.DiscreteModel.pdf "statsmodels.discrete.discrete_model.DiscreteModel.pdf")(X) | The probability density (mass) function of the model. |
| [`predict`](statsmodels.discrete.discrete_model.discretemodel.predict#statsmodels.discrete.discrete_model.DiscreteModel.predict "statsmodels.discrete.discrete_model.DiscreteModel.predict")(params[, exog, linear]) | Predict response variable of a model given exogenous variables. |
| [`score`](statsmodels.discrete.discrete_model.discretemodel.score#statsmodels.discrete.discrete_model.DiscreteModel.score "statsmodels.discrete.discrete_model.DiscreteModel.score")(params) | Score vector of model. |
#### Attributes
| | |
| --- | --- |
| `endog_names` | Names of endogenous variables |
| `exog_names` | Names of exogenous variables |
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.transform_params statsmodels.tsa.statespace.structural.UnobservedComponents.transform\_params
============================================================================
`UnobservedComponents.transform_params(unconstrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/structural.html#UnobservedComponents.transform_params)
Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation
statsmodels statsmodels.regression.linear_model.OLSResults.compare_lm_test statsmodels.regression.linear\_model.OLSResults.compare\_lm\_test
=================================================================
`OLSResults.compare_lm_test(restricted, demean=True, use_lr=False)`
Use Lagrange Multiplier test to test whether restricted model is correct
| Parameters: | * **restricted** (*Result instance*) β The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`.
* **demean** (*bool*) β Flag indicating whether the demean the scores based on the residuals from the restricted model. If True, the covariance of the scores are used and the LM test is identical to the large sample version of the LR test.
|
| Returns: | * **lm\_value** (*float*) β test statistic, chi2 distributed
* **p\_value** (*float*) β p-value of the test statistic
* **df\_diff** (*int*) β degrees of freedom of the restriction, i.e. difference in df between models
|
#### Notes
TODO: explain LM text
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.information statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.information
====================================================================
`DynamicFactor.information(params)`
Fisher information matrix of model
Returns -Hessian of loglike evaluated at params.
statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.information statsmodels.tsa.statespace.mlemodel.MLEModel.information
========================================================
`MLEModel.information(params)`
Fisher information matrix of model
Returns -Hessian of loglike evaluated at params.
statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.wald_test statsmodels.regression.mixed\_linear\_model.MixedLMResults.wald\_test
=====================================================================
`MixedLMResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)`
Compute a Wald-test for a joint linear hypothesis.
| Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) β
+ array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β Default is 1.0 for no scaling.
* **invcov** (*array-like**,* *optional*) β A q x q array to specify an inverse covariance matrix based on a restrictions matrix.
* **use\_f** (*bool*) β If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis.
|
| Returns: | **res** β The results for the test are attributes of this results instance. |
| Return type: | ContrastResults instance |
See also
[`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.regression.mixed_linear_model.mixedlmresults.f_test#statsmodels.regression.mixed_linear_model.MixedLMResults.f_test "statsmodels.regression.mixed_linear_model.MixedLMResults.f_test"), [`t_test`](statsmodels.regression.mixed_linear_model.mixedlmresults.t_test#statsmodels.regression.mixed_linear_model.MixedLMResults.t_test "statsmodels.regression.mixed_linear_model.MixedLMResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
#### Notes
The matrix `r_matrix` is assumed to be non-singular. More precisely,
r\_matrix (pX pX.T) r\_matrix.T
is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
statsmodels statsmodels.sandbox.stats.multicomp.randmvn statsmodels.sandbox.stats.multicomp.randmvn
===========================================
`statsmodels.sandbox.stats.multicomp.randmvn(rho, size=(1, 2), standardize=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#randmvn)
create random draws from equi-correlated multivariate normal distribution
| Parameters: | * **rho** (*float*) β correlation coefficient
* **size** (*tuple of int*) β size is interpreted (nobs, nvars) where each row
|
| Returns: | **rvs** β nobs by nvars where each row is a independent random draw of nvars- dimensional correlated rvs |
| Return type: | ndarray |
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.fittedvalues statsmodels.tsa.vector\_ar.var\_model.VARResults.fittedvalues
=============================================================
`VARResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.fittedvalues)
The predicted insample values of the response variables of the model.
statsmodels statsmodels.stats.multitest.fdrcorrection_twostage statsmodels.stats.multitest.fdrcorrection\_twostage
===================================================
`statsmodels.stats.multitest.fdrcorrection_twostage(pvals, alpha=0.05, method='bky', iter=False, is_sorted=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/multitest.html#fdrcorrection_twostage)
(iterated) two stage linear step-up procedure with estimation of number of true hypotheses
Benjamini, Krieger and Yekuteli, procedure in Definition 6
| Parameters: | * **pvals** (*array\_like*) β set of p-values of the individual tests.
* **alpha** (*float*) β error rate
* **method** (*{'bky'**,* *'bh'**)*) β see Notes for details
+ βbkyβ - implements the procedure in Definition 6 of Benjamini, Krieger and Yekuteli 2006
+ βbhβ - the two stage method of Benjamini and Hochberg
* **iter** (*bool*) β
|
| Returns: | * **rejected** (*array, bool*) β True if a hypothesis is rejected, False if not
* **pvalue-corrected** (*array*) β pvalues adjusted for multiple hypotheses testing to limit FDR
* **m0** (*int*) β ntest - rej, estimated number of true hypotheses
* **alpha\_stages** (*list of floats*) β A list of alphas that have been used at each stage
|
#### Notes
The returned corrected p-values are specific to the given alpha, they cannot be used for a different alpha.
The returned corrected p-values are from the last stage of the fdr\_bh linear step-up procedure (fdrcorrection0 with method=βindepβ) corrected for the estimated fraction of true hypotheses. This means that the rejection decision can be obtained with `pval_corrected <= alpha`, where `alpha` is the origianal significance level. (Note: This has changed from earlier versions (<0.5.0) of statsmodels.)
BKY described several other multi-stage methods, which would be easy to implement. However, in their simulation the simple two-stage method (with iter=False) was the most robust to the presence of positive correlation
TODO: What should be returned?
| programming_docs |
statsmodels statsmodels.graphics.gofplots.ProbPlot.sample_percentiles statsmodels.graphics.gofplots.ProbPlot.sample\_percentiles
==========================================================
`ProbPlot.sample_percentiles()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#ProbPlot.sample_percentiles)
statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.rvs statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.rvs
===========================================================
`SkewNorm2_gen.rvs(*args, **kwds)`
Random variates of given type.
| Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information).
* **loc** (*array\_like**,* *optional*) β Location parameter (default=0).
* **scale** (*array\_like**,* *optional*) β Scale parameter (default=1).
* **size** (*int* *or* *tuple of ints**,* *optional*) β Defining number of random variates (default is 1).
* **random\_state** (None or int or `np.random.RandomState` instance, optional) β If int or RandomState, use it for drawing the random variates. If None, rely on `self.random_state`. Default is None.
|
| Returns: | **rvs** β Random variates of given `size`. |
| Return type: | ndarray or scalar |
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_split statsmodels.genmod.generalized\_estimating\_equations.GEEResults.resid\_split
=============================================================================
`GEEResults.resid_split()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid_split)
Returns the residuals, the endogeneous data minus the fitted values from the model. The residuals are returned as a list of arrays containing the residuals for each cluster.
statsmodels statsmodels.genmod.families.links.nbinom.inverse_deriv statsmodels.genmod.families.links.nbinom.inverse\_deriv
=======================================================
`nbinom.inverse_deriv(z)`
Derivative of the inverse of the negative binomial transform
| Parameters: | **z** (*array-like*) β Usually the linear predictor for a GLM or GEE model |
| Returns: | **g^(-1)β(z)** β The value of the derivative of the inverse of the negative binomial link |
| Return type: | array |
statsmodels statsmodels.regression.linear_model.WLS.get_distribution statsmodels.regression.linear\_model.WLS.get\_distribution
==========================================================
`WLS.get_distribution(params, scale, exog=None, dist_class=None)`
Returns a random number generator for the predictive distribution.
| Parameters: | * **params** (*array-like*) β The model parameters (regression coefficients).
* **scale** (*scalar*) β The variance parameter.
* **exog** (*array-like*) β The predictor variable matrix.
* **dist\_class** (*class*) β A random number generator class. Must take βlocβ and βscaleβ as arguments and return a random number generator implementing an `rvs` method for simulating random values. Defaults to Gaussian.
|
| Returns: | Frozen random number generator object with mean and variance determined by the fitted linear model. Use the `rvs` method to generate random values. |
| Return type: | gen |
#### Notes
Due to the behavior of `scipy.stats.distributions objects`, the returned random number generator must be called with `gen.rvs(n)` where `n` is the number of observations in the data set used to fit the model. If any other value is used for `n`, misleading results will be produced.
statsmodels statsmodels.discrete.discrete_model.BinaryModel.fit_regularized statsmodels.discrete.discrete\_model.BinaryModel.fit\_regularized
=================================================================
`BinaryModel.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#BinaryModel.fit_regularized)
Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method.
| Parameters: | * **start\_params** (*array-like**,* *optional*) β Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros.
* **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) β See notes for details.
* **maxiter** (*Integer* *or* *'defined\_by\_method'*) β Maximum number of iterations to perform. If βdefined\_by\_methodβ, then use method defaults (see notes).
* **full\_output** (*bool*) β Set to True to have all available output in the Results objectβs mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information.
* **disp** (*bool*) β Set to True to print convergence messages.
* **fargs** (*tuple*) β Extra arguments passed to the likelihood function, i.e., loglike(x,\*args)
* **callback** (*callable callback**(**xk**)*) β Called after each iteration, as callback(xk), where xk is the current parameter vector.
* **retall** (*bool*) β Set to True to return list of solutions at each iteration. Available in Results objectβs mle\_retvals attribute.
* **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) β The weight multiplying the l1 penalty term
* **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) β If not βoffβ, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If βautoβ, trim params using the Theory above. If βsizeβ, trim params if they have very small absolute value
* **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) β For use when trim\_mode == βsizeβ
* **auto\_trim\_tol** (*float*) β For sue when trim\_mode == βautoβ. Use
* **qc\_tol** (*float*) β Print warning and donβt allow auto trim when (ii) (above) is violated by this much.
* **qc\_verbose** (*Boolean*) β If true, print out a full QC report upon failure
|
#### Notes
Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`.
Optional arguments for the solvers (available in Results.mle\_settings):
```
'l1'
acc : float (default 1e-6)
Requested accuracy as used by slsqp
'l1_cvxopt_cp'
abstol : float
absolute accuracy (default: 1e-7).
reltol : float
relative accuracy (default: 1e-6).
feastol : float
tolerance for feasibility conditions (default: 1e-7).
refinement : int
number of iterative refinement steps when solving KKT
equations (default: 1).
```
Optimization methodology
With \(L\) the negative log likelihood, we solve the convex but non-smooth problem
\[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the βadded variablesβ \(u\_k\))
\[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to
\[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds:
1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\)
2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\)
statsmodels statsmodels.sandbox.regression.gmm.GMM.score statsmodels.sandbox.regression.gmm.GMM.score
============================================
`GMM.score(params, weights, epsilon=None, centered=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.score)
statsmodels statsmodels.graphics.regressionplots.plot_fit statsmodels.graphics.regressionplots.plot\_fit
==============================================
`statsmodels.graphics.regressionplots.plot_fit(results, exog_idx, y_true=None, ax=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/regressionplots.html#plot_fit)
Plot fit against one regressor.
This creates one graph with the scatterplot of observed values compared to fitted values.
| Parameters: | * **results** (*result instance*) β result instance with resid, model.endog and model.exog as attributes
* **x\_var** (*int* *or* *str*) β Name or index of regressor in exog matrix.
* **y\_true** (*array\_like*) β (optional) If this is not None, then the array is added to the plot
* **ax** (*Matplotlib AxesSubplot instance**,* *optional*) β If given, this subplot is used to plot in instead of a new figure being created.
* **kwargs** β The keyword arguments are passed to the plot command for the fitted values points.
|
| Returns: | **fig** β If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. |
| Return type: | Matplotlib figure instance |
#### Examples
Load the Statewide Crime data set and perform linear regression with `poverty` and `hs_grad` as variables and `murder` as the response
```
>>> import statsmodels.api as sm
>>> import matplotlib.pyplot as plt
```
```
>>> data = sm.datasets.statecrime.load_pandas().data
>>> murder = data['murder']
>>> X = data[['poverty', 'hs_grad']]
```
```
>>> X["constant"] = 1
>>> y = murder
>>> model = sm.OLS(y, X)
>>> results = model.fit()
```
Create a plot just for the variable βPovertyβ:
```
>>> fig, ax = plt.subplots()
>>> fig = sm.graphics.plot_fit(results, 0, ax=ax)
>>> ax.set_ylabel("Murder Rate")
>>> ax.set_xlabel("Poverty Level")
>>> ax.set_title("Linear Regression")
```
```
>>> plt.show()
```
([Source code](../plots/graphics_plot_fit_ex.py), [png](../plots/graphics_plot_fit_ex.png), [hires.png](../plots/graphics_plot_fit_ex.hires.png), [pdf](../plots/graphics_plot_fit_ex.pdf))
statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.wresid statsmodels.sandbox.regression.gmm.IVRegressionResults.wresid
=============================================================
`IVRegressionResults.wresid()`
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.bic statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.bic
===================================================================
`DynamicFactorResults.bic()`
(float) Bayes Information Criterion
statsmodels statsmodels.duration.survfunc.SurvfuncRight.summary statsmodels.duration.survfunc.SurvfuncRight.summary
===================================================
`SurvfuncRight.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/survfunc.html#SurvfuncRight.summary)
Return a summary of the estimated survival function.
The summary is a datafram containing the unique event times, estimated survival function values, and related quantities.
statsmodels statsmodels.genmod.families.links.CLogLog.inverse_deriv statsmodels.genmod.families.links.CLogLog.inverse\_deriv
========================================================
`CLogLog.inverse_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#CLogLog.inverse_deriv)
Derivative of the inverse of the C-Log-Log transform link function
| Parameters: | **z** (*array-like*) β The value of the inverse of the CLogLog link function at `p` |
| Returns: | **g^(-1)β(z)** β The derivative of the inverse of the CLogLog link function |
| Return type: | array |
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.conf_int statsmodels.regression.recursive\_ls.RecursiveLSResults.conf\_int
=================================================================
`RecursiveLSResults.conf_int(alpha=0.05, cols=None, method='default')`
Returns the confidence interval of the fitted parameters.
| Parameters: | * **alpha** (*float**,* *optional*) β The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval.
* **cols** (*array-like**,* *optional*) β `cols` specifies which confidence intervals to return
* **method** (*string*) β Not Implemented Yet Method to estimate the confidence\_interval. βDefaultβ : uses self.bse which is based on inverse Hessian for MLE βhjjhβ : βjacβ : βboot-bseβ βboot\_quantβ βprofileβ
|
| Returns: | **conf\_int** β Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. |
| Return type: | array |
#### Examples
```
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> results.conf_int()
array([[-5496529.48322745, -1467987.78596704],
[ -177.02903529, 207.15277984],
[ -0.1115811 , 0.03994274],
[ -3.12506664, -0.91539297],
[ -1.5179487 , -0.54850503],
[ -0.56251721, 0.460309 ],
[ 798.7875153 , 2859.51541392]])
```
```
>>> results.conf_int(cols=(2,3))
array([[-0.1115811 , 0.03994274],
[-3.12506664, -0.91539297]])
```
#### Notes
The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method.
statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.freeze statsmodels.sandbox.distributions.transformed.Transf\_gen.freeze
================================================================
`Transf_gen.freeze(*args, **kwds)`
Freeze the distribution for the given arguments.
| Parameters: | **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution. Should include all the non-optional arguments, may include `loc` and `scale`. |
| Returns: | **rv\_frozen** β The frozen distribution. |
| Return type: | rv\_frozen instance |
statsmodels statsmodels.sandbox.regression.gmm.IV2SLS statsmodels.sandbox.regression.gmm.IV2SLS
=========================================
`class statsmodels.sandbox.regression.gmm.IV2SLS(endog, exog, instrument=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IV2SLS)
Instrumental variables estimation using Two-Stage Least-Squares (2SLS)
| Parameters: | * **endog** (*array*) β Endogenous variable, 1-dimensional or 2-dimensional array nobs by 1
* **exog** (*array*) β Explanatory variables, 1-dimensional or 2-dimensional array nobs by k
* **instrument** (*array*) β Instruments for explanatory variables. Must contain both exog variables that are not being instrumented and instruments
|
#### Notes
All variables in exog are instrumented in the calculations. If variables in exog are not supposed to be instrumented, then these variables must also to be included in the instrument array.
Degrees of freedom in the calculation of the standard errors uses `df_resid = (nobs - k_vars)`. (This corresponds to the `small` option in Stataβs ivreg2.)
#### Methods
| | |
| --- | --- |
| [`fit`](statsmodels.sandbox.regression.gmm.iv2sls.fit#statsmodels.sandbox.regression.gmm.IV2SLS.fit "statsmodels.sandbox.regression.gmm.IV2SLS.fit")() | estimate model using 2SLS IV regression |
| [`from_formula`](statsmodels.sandbox.regression.gmm.iv2sls.from_formula#statsmodels.sandbox.regression.gmm.IV2SLS.from_formula "statsmodels.sandbox.regression.gmm.IV2SLS.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. |
| [`hessian`](statsmodels.sandbox.regression.gmm.iv2sls.hessian#statsmodels.sandbox.regression.gmm.IV2SLS.hessian "statsmodels.sandbox.regression.gmm.IV2SLS.hessian")(params) | The Hessian matrix of the model |
| [`information`](statsmodels.sandbox.regression.gmm.iv2sls.information#statsmodels.sandbox.regression.gmm.IV2SLS.information "statsmodels.sandbox.regression.gmm.IV2SLS.information")(params) | Fisher information matrix of model |
| [`initialize`](statsmodels.sandbox.regression.gmm.iv2sls.initialize#statsmodels.sandbox.regression.gmm.IV2SLS.initialize "statsmodels.sandbox.regression.gmm.IV2SLS.initialize")() | Initialize (possibly re-initialize) a Model instance. |
| [`loglike`](statsmodels.sandbox.regression.gmm.iv2sls.loglike#statsmodels.sandbox.regression.gmm.IV2SLS.loglike "statsmodels.sandbox.regression.gmm.IV2SLS.loglike")(params) | Log-likelihood of model. |
| [`predict`](statsmodels.sandbox.regression.gmm.iv2sls.predict#statsmodels.sandbox.regression.gmm.IV2SLS.predict "statsmodels.sandbox.regression.gmm.IV2SLS.predict")(params[, exog]) | Return linear predicted values from a design matrix. |
| [`score`](statsmodels.sandbox.regression.gmm.iv2sls.score#statsmodels.sandbox.regression.gmm.IV2SLS.score "statsmodels.sandbox.regression.gmm.IV2SLS.score")(params) | Score vector of model. |
| [`whiten`](statsmodels.sandbox.regression.gmm.iv2sls.whiten#statsmodels.sandbox.regression.gmm.IV2SLS.whiten "statsmodels.sandbox.regression.gmm.IV2SLS.whiten")(X) | |
#### Attributes
| | |
| --- | --- |
| `endog_names` | Names of endogenous variables |
| `exog_names` | Names of exogenous variables |
statsmodels statsmodels.regression.quantile_regression.QuantReg.get_distribution statsmodels.regression.quantile\_regression.QuantReg.get\_distribution
======================================================================
`QuantReg.get_distribution(params, scale, exog=None, dist_class=None)`
Returns a random number generator for the predictive distribution.
| Parameters: | * **params** (*array-like*) β The model parameters (regression coefficients).
* **scale** (*scalar*) β The variance parameter.
* **exog** (*array-like*) β The predictor variable matrix.
* **dist\_class** (*class*) β A random number generator class. Must take βlocβ and βscaleβ as arguments and return a random number generator implementing an `rvs` method for simulating random values. Defaults to Gaussian.
|
| Returns: | Frozen random number generator object with mean and variance determined by the fitted linear model. Use the `rvs` method to generate random values. |
| Return type: | gen |
#### Notes
Due to the behavior of `scipy.stats.distributions objects`, the returned random number generator must be called with `gen.rvs(n)` where `n` is the number of observations in the data set used to fit the model. If any other value is used for `n`, misleading results will be produced.
statsmodels statsmodels.nonparametric.kde.KDEUnivariate.fit statsmodels.nonparametric.kde.KDEUnivariate.fit
===============================================
`KDEUnivariate.fit(kernel='gau', bw='normal_reference', fft=True, weights=None, gridsize=None, adjust=1, cut=3, clip=(-inf, inf))` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kde.html#KDEUnivariate.fit)
Attach the density estimate to the KDEUnivariate class.
| Parameters: | * **kernel** (*str*) β The Kernel to be used. Choices are:
+ βbiwβ for biweight
+ βcosβ for cosine
+ βepaβ for Epanechnikov
+ βgauβ for Gaussian.
+ βtriβ for triangular
+ βtriwβ for triweight
+ βuniβ for uniform
* **bw** (*str**,* *float*) β The bandwidth to use. Choices are:
+ βscottβ - 1.059 \* A \* nobs \*\* (-1/5.), where A is `min(std(X),IQR/1.34)`
+ βsilvermanβ - .9 \* A \* nobs \*\* (-1/5.), where A is `min(std(X),IQR/1.34)`
+ βnormal\_referenceβ - C \* A \* nobs \*\* (-1/5.), where C is calculated from the kernel. Equivalent (up to 2 dp) to the βscottβ bandwidth for gaussian kernels. See bandwidths.py
+ If a float is given, it is the bandwidth.
* **fft** (*bool*) β Whether or not to use FFT. FFT implementation is more computationally efficient. However, only the Gaussian kernel is implemented. If FFT is False, then a βnobsβ x βgridsizeβ intermediate array is created.
* **gridsize** (*int*) β If gridsize is None, max(len(X), 50) is used.
* **cut** (*float*) β Defines the length of the grid past the lowest and highest values of X so that the kernel goes to zero. The end points are -/+ cut\*bw\*{min(X) or max(X)}
* **adjust** (*float*) β An adjustment factor for the bw. Bandwidth becomes bw \* adjust.
|
| programming_docs |
statsmodels statsmodels.discrete.discrete_model.ProbitResults.save statsmodels.discrete.discrete\_model.ProbitResults.save
=======================================================
`ProbitResults.save(fname, remove_data=False)`
save a pickle of this instance
| Parameters: | * **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle.
* **remove\_data** (*bool*) β If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None.
|
#### Notes
If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception.
statsmodels statsmodels.discrete.discrete_model.ProbitResults.predict statsmodels.discrete.discrete\_model.ProbitResults.predict
==========================================================
`ProbitResults.predict(exog=None, transform=True, *args, **kwargs)`
Call self.model.predict with self.params as the first argument.
| Parameters: | * **exog** (*array-like**,* *optional*) β The values for which you want to predict. see Notes below.
* **transform** (*bool**,* *optional*) β If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, youβd need to log the data first.
* **kwargs** (*args**,*) β Some models can take additional arguments or keywords, see the predict method of the model for the details.
|
| Returns: | **prediction** β See self.model.predict |
| Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") |
#### Notes
The types of exog that are supported depends on whether a formula was used in the specification of the model.
If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object.
If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array.
Row indices as in pandas data frames are supported, and added to the returned prediction.
statsmodels statsmodels.multivariate.cancorr.CanCorr.fit statsmodels.multivariate.cancorr.CanCorr.fit
============================================
`CanCorr.fit()`
Fit a model to data.
statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.errband_mc statsmodels.tsa.vector\_ar.irf.IRAnalysis.errband\_mc
=====================================================
`IRAnalysis.errband_mc(orth=False, svar=False, repl=1000, signif=0.05, seed=None, burn=100)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.errband_mc)
IRF Monte Carlo integrated error bands
statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.rsquared statsmodels.sandbox.regression.gmm.IVRegressionResults.rsquared
===============================================================
`IVRegressionResults.rsquared()`
statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.information statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.information
=================================================================================
`MarkovRegression.information(params)`
Fisher information matrix of model
Returns -Hessian of loglike evaluated at params.
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.normalized_cov_params statsmodels.regression.recursive\_ls.RecursiveLSResults.normalized\_cov\_params
===============================================================================
`RecursiveLSResults.normalized_cov_params()`
statsmodels statsmodels.regression.linear_model.OLSResults.wald_test statsmodels.regression.linear\_model.OLSResults.wald\_test
==========================================================
`OLSResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)`
Compute a Wald-test for a joint linear hypothesis.
| Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) β
+ array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β Default is 1.0 for no scaling.
* **invcov** (*array-like**,* *optional*) β A q x q array to specify an inverse covariance matrix based on a restrictions matrix.
* **use\_f** (*bool*) β If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis.
|
| Returns: | **res** β The results for the test are attributes of this results instance. |
| Return type: | ContrastResults instance |
See also
[`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.regression.linear_model.olsresults.f_test#statsmodels.regression.linear_model.OLSResults.f_test "statsmodels.regression.linear_model.OLSResults.f_test"), [`t_test`](statsmodels.regression.linear_model.olsresults.t_test#statsmodels.regression.linear_model.OLSResults.t_test "statsmodels.regression.linear_model.OLSResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
#### Notes
The matrix `r_matrix` is assumed to be non-singular. More precisely,
r\_matrix (pX pX.T) r\_matrix.T
is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond
======================================================
`LinearIVGMM.momcond(params)`
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.loglikelihood_burn statsmodels.tsa.statespace.structural.UnobservedComponentsResults.loglikelihood\_burn
=====================================================================================
`UnobservedComponentsResults.loglikelihood_burn()`
(float) The number of observations during which the likelihood is not evaluated.
statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.resid_pearson statsmodels.genmod.generalized\_linear\_model.GLMResults.resid\_pearson
=======================================================================
`GLMResults.resid_pearson()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.resid_pearson)
statsmodels statsmodels.regression.quantile_regression.QuantRegResults.remove_data statsmodels.regression.quantile\_regression.QuantRegResults.remove\_data
========================================================================
`QuantRegResults.remove_data()`
remove data arrays, all nobs arrays from result and model
This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.
Warning
Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.
Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.
The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data.
The attributes to remove are named in:
`model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name.
`result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name)
`result._data_attr_model : arrays attached to the model` instance but not to the results instance
statsmodels statsmodels.regression.quantile_regression.QuantReg.from_formula statsmodels.regression.quantile\_regression.QuantReg.from\_formula
==================================================================
`classmethod QuantReg.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)`
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_approx statsmodels.regression.recursive\_ls.RecursiveLSResults.cov\_params\_approx
===========================================================================
`RecursiveLSResults.cov_params_approx()`
(array) The variance / covariance matrix. Computed using the numerical Hessian approximated by complex step or finite differences methods.
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.cusum statsmodels.regression.recursive\_ls.RecursiveLSResults.cusum
=============================================================
`RecursiveLSResults.cusum()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLSResults.cusum)
Cumulative sum of standardized recursive residuals statistics
| Returns: | **cusum** β An array of length `nobs - k_exog` holding the CUSUM statistics. |
| Return type: | array\_like |
#### Notes
The CUSUM statistic takes the form:
\[W\_t = \frac{1}{\hat \sigma} \sum\_{j=k+1}^t w\_j\] where \(w\_j\) is the recursive residual at time \(j\) and \(\hat \sigma\) is the estimate of the standard deviation from the full sample.
Excludes the first `k_exog` datapoints.
Due to differences in the way \(\hat \sigma\) is calculated, the output of this function differs slightly from the output in the R package strucchange and the Stata contributed .ado file cusum6. The calculation in this package is consistent with the description of Brown et al. (1975)
#### References
| | |
| --- | --- |
| [\*] | Brown, R. L., J. Durbin, and J. M. Evans. 1975. βTechniques for Testing the Constancy of Regression Relationships over Time.β Journal of the Royal Statistical Society. Series B (Methodological) 37 (2): 149-92. |
statsmodels statsmodels.discrete.discrete_model.Logit.cdf statsmodels.discrete.discrete\_model.Logit.cdf
==============================================
`Logit.cdf(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Logit.cdf)
The logistic cumulative distribution function
| Parameters: | **X** (*array-like*) β `X` is the linear predictor of the logit model. See notes. |
| Returns: | |
| Return type: | 1/(1 + exp(-X)) |
#### Notes
In the logit model,
\[\Lambda\left(x^{\prime}\beta\right)=\text{Prob}\left(Y=1|x\right)=\frac{e^{x^{\prime}\beta}}{1+e^{x^{\prime}\beta}}\]
statsmodels statsmodels.genmod.families.family.NegativeBinomial.loglike_obs statsmodels.genmod.families.family.NegativeBinomial.loglike\_obs
================================================================
`NegativeBinomial.loglike_obs(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#NegativeBinomial.loglike_obs)
The log-likelihood function for each observation in terms of the fitted mean response for the Negative Binomial distribution.
| Parameters: | * **endog** (*array*) β Usually the endogenous response variable.
* **mu** (*array*) β Usually but not always the fitted mean response variable.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **scale** (*float*) β The scale parameter. The default is 1.
|
| Returns: | **ll\_i** β The value of the loglikelihood evaluated at (endog, mu, var\_weights, scale) as defined below. |
| Return type: | float |
#### Notes
Defined as:
\[llf = \sum\_i var\\_weights\_i / scale \* (Y\_i \* \log{(\alpha \* \mu\_i / (1 + \alpha \* \mu\_i))} - \log{(1 + \alpha \* \mu\_i)}/ \alpha + Constant)\] where \(Constant\) is defined as:
\[Constant = \ln \Gamma{(Y\_i + 1/ \alpha )} - \ln \Gamma(Y\_i + 1) - \ln \Gamma{(1/ \alpha )}\] constant = (special.gammaln(endog + 1 / self.alpha) - special.gammaln(endog+1)-special.gammaln(1/self.alpha)) return (endog \* np.log(self.alpha \* mu / (1 + self.alpha \* mu)) - np.log(1 + self.alpha \* mu) / self.alpha + constant) \* var\_weights / scale
statsmodels statsmodels.tsa.stattools.ccf statsmodels.tsa.stattools.ccf
=============================
`statsmodels.tsa.stattools.ccf(x, y, unbiased=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#ccf)
cross-correlation function for 1d
| Parameters: | * **y** (*x**,*) β time series data
* **unbiased** (*boolean*) β if True, then denominators for autocovariance is n-k, otherwise n
|
| Returns: | **ccf** β cross-correlation function of x and y |
| Return type: | array |
#### Notes
This is based np.correlate which does full convolution. For very long time series it is recommended to use fft convolution instead.
If unbiased is true, the denominator for the autocovariance is adjusted but the autocorrelation is not an unbiased estimtor.
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.bic statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.bic
===========================================================================
`ZeroInflatedGeneralizedPoissonResults.bic()`
statsmodels statsmodels.discrete.discrete_model.CountResults.load statsmodels.discrete.discrete\_model.CountResults.load
======================================================
`classmethod CountResults.load(fname)`
load a pickle, (class method)
| Parameters: | **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle. |
| Returns: | |
| Return type: | unpickled instance |
statsmodels statsmodels.discrete.discrete_model.MultinomialResults.cov_params statsmodels.discrete.discrete\_model.MultinomialResults.cov\_params
===================================================================
`MultinomialResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)`
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar.
| Parameters: | * **r\_matrix** (*array-like*) β Can be 1d, or 2d. Can be used alone or with other.
* **column** (*array-like**,* *optional*) β Must be used on its own. Can be 0d or 1d see below.
* **scale** (*float**,* *optional*) β Can be specified or not. Default is None, which means that the scale argument is taken from the model.
* **other** (*array-like**,* *optional*) β Can be used when r\_matrix is specified.
|
| Returns: | **cov** β covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. |
| Return type: | ndarray |
#### Notes
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)`
If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T`
If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T`
If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d
OR
`(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d
statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.bse statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.bse
==================================================================
`GeneralizedPoissonResults.bse()`
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor
========================================================
`class statsmodels.tsa.statespace.dynamic_factor.DynamicFactor(endog, k_factors, factor_order, exog=None, error_order=0, error_var=False, error_cov_type='diagonal', enforce_stationarity=True, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/dynamic_factor.html#DynamicFactor)
Dynamic factor model
| Parameters: | * **endog** (*array\_like*) β The observed time-series process \(y\)
* **exog** (*array\_like**,* *optional*) β Array of exogenous regressors for the observation equation, shaped nobs x k\_exog.
* **k\_factors** (*int*) β The number of unobserved factors.
* **factor\_order** (*int*) β The order of the vector autoregression followed by the factors.
* **error\_cov\_type** (*{'scalar'**,* *'diagonal'**,* *'unstructured'}**,* *optional*) β The structure of the covariance matrix of the observation error term, where βunstructuredβ puts no restrictions on the matrix, βdiagonalβ requires it to be any diagonal matrix (uncorrelated errors), and βscalarβ requires it to be a scalar times the identity matrix. Default is βdiagonalβ.
* **error\_order** (*int**,* *optional*) β The order of the vector autoregression followed by the observation error component. Default is None, corresponding to white noise errors.
* **error\_var** (*boolean**,* *optional*) β Whether or not to model the errors jointly via a vector autoregression, rather than as individual autoregressions. Has no effect unless `error_order` is set. Default is False.
* **enforce\_stationarity** (*boolean**,* *optional*) β Whether or not to transform the AR parameters to enforce stationarity in the autoregressive component of the model. Default is True.
* **\*\*kwargs** β Keyword arguments may be used to provide default values for state space matrices or for Kalman filtering options. See `Representation`, and `KalmanFilter` for more details.
|
`exog`
*array\_like, optional* β Array of exogenous regressors for the observation equation, shaped nobs x k\_exog.
`k_factors`
*int* β The number of unobserved factors.
`factor_order`
*int* β The order of the vector autoregression followed by the factors.
`error_cov_type`
*{βdiagonalβ, βunstructuredβ}* β The structure of the covariance matrix of the error term, where βunstructuredβ puts no restrictions on the matrix and βdiagonalβ requires it to be a diagonal matrix (uncorrelated errors).
`error_order`
*int* β The order of the vector autoregression followed by the observation error component.
`error_var`
*boolean* β Whether or not to model the errors jointly via a vector autoregression, rather than as individual autoregressions. Has no effect unless `error_order` is set.
`enforce_stationarity`
*boolean, optional* β Whether or not to transform the AR parameters to enforce stationarity in the autoregressive component of the model. Default is True.
#### Notes
The dynamic factor model considered here is in the so-called static form, and is specified:
\[\begin{split}y\_t & = \Lambda f\_t + B x\_t + u\_t \\ f\_t & = A\_1 f\_{t-1} + \dots + A\_p f\_{t-p} + \eta\_t \\ u\_t & = C\_1 u\_{t-1} + \dots + C\_1 f\_{t-q} + \varepsilon\_t\end{split}\] where there are `k_endog` observed series and `k_factors` unobserved factors. Thus \(y\_t\) is a `k_endog` x 1 vector and \(f\_t\) is a `k_factors` x 1 vector.
\(x\_t\) are optional exogenous vectors, shaped `k_exog` x 1.
\(\eta\_t\) and \(\varepsilon\_t\) are white noise error terms. In order to identify the factors, \(Var(\eta\_t) = I\). Denote \(Var(\varepsilon\_t) \equiv \Sigma\).
Options related to the unobserved factors:
* `k_factors`: this is the dimension of the vector \(f\_t\), above. To exclude factors completely, set `k_factors = 0`.
* `factor_order`: this is the number of lags to include in the factor evolution equation, and corresponds to \(p\), above. To have static factors, set `factor_order = 0`.
Options related to the observation error term \(u\_t\):
* `error_order`: the number of lags to include in the error evolution equation; corresponds to \(q\), above. To have white noise errors, set `error_order = 0` (this is the default).
* `error_cov_type`: this controls the form of the covariance matrix \(\Sigma\). If it is βdscalarβ, then \(\Sigma = \sigma^2 I\). If it is βdiagonalβ, then \(\Sigma = \text{diag}(\sigma\_1^2, \dots, \sigma\_n^2)\). If it is βunstructuredβ, then \(\Sigma\) is any valid variance / covariance matrix (i.e. symmetric and positive definite).
* `error_var`: this controls whether or not the errors evolve jointly according to a VAR(q), or individually according to separate AR(q) processes. In terms of the formulation above, if `error_var = False`, then the matrices :math:C\_i` are diagonal, otherwise they are general VAR matrices.
#### References
| | |
| --- | --- |
| [\*] | LΓΌtkepohl, Helmut. 2007. New Introduction to Multiple Time Series Analysis. Berlin: Springer. |
#### Methods
| | |
| --- | --- |
| [`filter`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.filter#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.filter "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.filter")(params[, transformed, complex\_step, β¦]) | Kalman filtering |
| [`fit`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.fit#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.fit "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.fit")([start\_params, transformed, cov\_type, β¦]) | Fits the model by maximum likelihood via Kalman filter. |
| [`from_formula`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.from_formula#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.from_formula "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.from_formula")(formula, data[, subset]) | Not implemented for state space models |
| [`hessian`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.hessian#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.hessian "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.hessian")(params, \*args, \*\*kwargs) | Hessian matrix of the likelihood function, evaluated at the given parameters |
| [`impulse_responses`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.impulse_responses#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.impulse_responses "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.impulse_responses")(params[, steps, impulse, β¦]) | Impulse response function |
| [`information`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.information#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.information "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.information")(params) | Fisher information matrix of model |
| [`initialize`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.initialize#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize")() | Initialize (possibly re-initialize) a Model instance. |
| [`initialize_approximate_diffuse`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.initialize_approximate_diffuse#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_approximate_diffuse "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_approximate_diffuse")([variance]) | |
| [`initialize_known`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.initialize_known#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_known "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_known")(initial\_state, β¦) | |
| [`initialize_statespace`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.initialize_statespace#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_statespace "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_statespace")(\*\*kwargs) | Initialize the state space representation |
| [`initialize_stationary`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.initialize_stationary#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_stationary "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_stationary")() | |
| [`loglike`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.loglike#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.loglike "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.loglike")(params, \*args, \*\*kwargs) | Loglikelihood evaluation |
| [`loglikeobs`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.loglikeobs#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.loglikeobs "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.loglikeobs")(params[, transformed, complex\_step]) | Loglikelihood evaluation |
| [`observed_information_matrix`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.observed_information_matrix#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.observed_information_matrix "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.observed_information_matrix")(params[, β¦]) | Observed information matrix |
| [`opg_information_matrix`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.opg_information_matrix#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.opg_information_matrix "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.opg_information_matrix")(params[, β¦]) | Outer product of gradients information matrix |
| [`predict`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.predict#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.predict "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. |
| [`prepare_data`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.prepare_data#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.prepare_data "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.prepare_data")() | Prepare data for use in the state space representation |
| [`score`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.score#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.score "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.score")(params, \*args, \*\*kwargs) | Compute the score function at params. |
| [`score_obs`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.score_obs#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.score_obs "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.score_obs")(params[, method, transformed, β¦]) | Compute the score per observation, evaluated at params |
| [`set_conserve_memory`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.set_conserve_memory#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_conserve_memory "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_conserve_memory")([conserve\_memory]) | Set the memory conservation method |
| [`set_filter_method`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.set_filter_method#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_filter_method "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_filter_method")([filter\_method]) | Set the filtering method |
| [`set_inversion_method`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.set_inversion_method#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_inversion_method "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_inversion_method")([inversion\_method]) | Set the inversion method |
| [`set_smoother_output`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.set_smoother_output#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_smoother_output "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_smoother_output")([smoother\_output]) | Set the smoother output |
| [`set_stability_method`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.set_stability_method#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_stability_method "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_stability_method")([stability\_method]) | Set the numerical stability method |
| [`simulate`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.simulate#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.simulate "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.simulate")(params, nsimulations[, β¦]) | Simulate a new time series following the state space model |
| [`simulation_smoother`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.simulation_smoother#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.simulation_smoother "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.simulation_smoother")([simulation\_output]) | Retrieve a simulation smoother for the state space model. |
| [`smooth`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.smooth#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.smooth "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.smooth")(params[, transformed, complex\_step, β¦]) | Kalman smoothing |
| [`transform_jacobian`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.transform_jacobian#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.transform_jacobian "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.transform_jacobian")(unconstrained[, β¦]) | Jacobian matrix for the parameter transformation function |
| [`transform_params`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.transform_params#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.transform_params "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.transform_params")(unconstrained) | Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation |
| [`untransform_params`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.untransform_params#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.untransform_params "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.untransform_params")(constrained) | Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer. |
| [`update`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.update#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.update "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.update")(params[, transformed, complex\_step]) | Update the parameters of the model |
#### Attributes
| | |
| --- | --- |
| `endog_names` | Names of endogenous variables |
| `exog_names` | |
| `initial_variance` | |
| `initialization` | |
| `loglikelihood_burn` | |
| `param_names` | (list of str) List of human readable parameter names (for parameters actually included in the model). |
| `start_params` | (array) Starting parameters for maximum likelihood estimation. |
| `tolerance` | |
| programming_docs |
statsmodels statsmodels.discrete.discrete_model.LogitResults.llr_pvalue statsmodels.discrete.discrete\_model.LogitResults.llr\_pvalue
=============================================================
`LogitResults.llr_pvalue()`
statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.aic statsmodels.tsa.statespace.varmax.VARMAXResults.aic
===================================================
`VARMAXResults.aic()`
(float) Akaike Information Criterion
statsmodels statsmodels.stats.outliers_influence.OLSInfluence.cooks_distance statsmodels.stats.outliers\_influence.OLSInfluence.cooks\_distance
==================================================================
`OLSInfluence.cooks_distance()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.cooks_distance)
(cached attribute) Cooks distance
uses original results, no nobs loop
statsmodels statsmodels.stats.outliers_influence.OLSInfluence.hat_matrix_diag statsmodels.stats.outliers\_influence.OLSInfluence.hat\_matrix\_diag
====================================================================
`OLSInfluence.hat_matrix_diag()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.hat_matrix_diag)
(cached attribute) diagonal of the hat\_matrix for OLS
#### Notes
temporarily calculated here, this should go to model class
statsmodels statsmodels.discrete.discrete_model.DiscreteResults.pvalues statsmodels.discrete.discrete\_model.DiscreteResults.pvalues
============================================================
`DiscreteResults.pvalues()`
statsmodels statsmodels.genmod.generalized_linear_model.GLM.fit_regularized statsmodels.genmod.generalized\_linear\_model.GLM.fit\_regularized
==================================================================
`GLM.fit_regularized(method='elastic_net', alpha=0.0, start_params=None, refit=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.fit_regularized)
Return a regularized fit to a linear regression model.
| Parameters: | * **method** β Only the `elastic_net` approach is currently implemented.
* **alpha** (*scalar* *or* *array-like*) β The penalty weight. If a scalar, the same penalty weight applies to all variables in the model. If a vector, it must have the same length as `params`, and contains a penalty weight for each coefficient.
* **start\_params** (*array-like*) β Starting values for `params`.
* **refit** (*bool*) β If True, the model is refit using only the variables that have non-zero coefficients in the regularized fit. The refitted model is not regularized.
|
| Returns: | |
| Return type: | An array, or a GLMResults object of the same type returned by `fit`. |
#### Notes
The penalty is the `elastic net` penalty, which is a combination of L1 and L2 penalties.
The function that is minimized is:
\[-loglike/n + alpha\*((1-L1\\_wt)\*|params|\_2^2/2 + L1\\_wt\*|params|\_1)\] where \(|\*|\_1\) and \(|\*|\_2\) are the L1 and L2 norms.
Post-estimation results are based on the same data used to select variables, hence may be subject to overfitting biases.
The elastic\_net method uses the following keyword arguments:
`maxiter : int` Maximum number of iterations
`L1_wt : float` Must be in [0, 1]. The L1 penalty has weight L1\_wt and the L2 penalty has weight 1 - L1\_wt.
`cnvrg_tol : float` Convergence threshold for line searches
`zero_tol : float` Coefficients below this threshold are treated as zero.
statsmodels statsmodels.sandbox.stats.multicomp.StepDown.check_set statsmodels.sandbox.stats.multicomp.StepDown.check\_set
=======================================================
`StepDown.check_set(indices)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#StepDown.check_set)
check whether pairwise distances of indices satisfy condition
statsmodels statsmodels.discrete.discrete_model.LogitResults.load statsmodels.discrete.discrete\_model.LogitResults.load
======================================================
`classmethod LogitResults.load(fname)`
load a pickle, (class method)
| Parameters: | **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle. |
| Returns: | |
| Return type: | unpickled instance |
statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.stats statsmodels.sandbox.distributions.extras.ACSkewT\_gen.stats
===========================================================
`ACSkewT_gen.stats(*args, **kwds)`
Some statistics of the given RV.
| Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional* *(**continuous RVs only**)*) β scale parameter (default=1)
* **moments** (*str**,* *optional*) β composed of letters [βmvskβ] defining which moments to compute: βmβ = mean, βvβ = variance, βsβ = (Fisherβs) skew, βkβ = (Fisherβs) kurtosis. (default is βmvβ)
|
| Returns: | **stats** β of requested moments. |
| Return type: | sequence |
statsmodels statsmodels.stats.weightstats._zstat_generic2 statsmodels.stats.weightstats.\_zstat\_generic2
===============================================
`statsmodels.stats.weightstats._zstat_generic2(value, std_diff, alternative)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#_zstat_generic2)
generic (normal) z-test to save typing
can be used as ztest based on summary statistics
statsmodels statsmodels.genmod.generalized_linear_model.GLM.from_formula statsmodels.genmod.generalized\_linear\_model.GLM.from\_formula
===============================================================
`classmethod GLM.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)`
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.cdf statsmodels.sandbox.distributions.transformed.Transf\_gen.cdf
=============================================================
`Transf_gen.cdf(x, *args, **kwds)`
Cumulative distribution function of the given RV.
| Parameters: | * **x** (*array\_like*) β quantiles
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
| Returns: | **cdf** β Cumulative distribution function evaluated at `x` |
| Return type: | ndarray |
statsmodels statsmodels.tsa.statespace.representation.Representation.initialize_known statsmodels.tsa.statespace.representation.Representation.initialize\_known
==========================================================================
`Representation.initialize_known(initial_state, initial_state_cov)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/representation.html#Representation.initialize_known)
Initialize the statespace model with known distribution for initial state.
These values are assumed to be known with certainty or else filled with parameters during, for example, maximum likelihood estimation.
| Parameters: | * **initial\_state** (*array\_like*) β Known mean of the initial state vector.
* **initial\_state\_cov** (*array\_like*) β Known covariance matrix of the initial state vector.
|
statsmodels statsmodels.regression.mixed_linear_model.MixedLM.fit statsmodels.regression.mixed\_linear\_model.MixedLM.fit
=======================================================
`MixedLM.fit(start_params=None, reml=True, niter_sa=0, do_cg=True, fe_pen=None, cov_pen=None, free=None, full_output=False, method='bfgs', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.fit)
Fit a linear mixed model to the data.
| Parameters: | * **start\_params** (*array-like* *or* *MixedLMParams*) β Starting values for the profile log-likelihood. If not a `MixedLMParams` instance, this should be an array containing the packed parameters for the profile log-likelihood, including the fixed effects parameters.
* **reml** (*bool*) β If true, fit according to the REML likelihood, else fit the standard likelihood using ML.
* **niter\_sa** β Currently this argument is ignored and has no effect on the results.
* **cov\_pen** (*CovariancePenalty object*) β A penalty for the random effects covariance matrix
* **do\_cg** (*boolean**,* *defaults to True*) β If False, the optimization is skipped and a results object at the given (or default) starting values is returned.
* **fe\_pen** (*Penalty object*) β A penalty on the fixed effects
* **free** (*MixedLMParams object*) β If not `None`, this is a mask that allows parameters to be held fixed at specified values. A 1 indicates that the correspondinig parameter is estimated, a 0 indicates that it is fixed at its starting value. Setting the `cov_re` component to the identity matrix fits a model with independent random effects. Note that some optimization methods do not respect this constraint (bfgs and lbfgs both work).
* **full\_output** (*bool*) β If true, attach iteration history to results
* **method** (*string*) β Optimization method.
|
| Returns: | |
| Return type: | A MixedLMResults instance. |
statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.plot_acorr statsmodels.tsa.vector\_ar.var\_model.VARProcess.plot\_acorr
============================================================
`VARProcess.plot_acorr(nlags=10, linewidth=8)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.plot_acorr)
Plot theoretical autocorrelation function
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.set_stability_method statsmodels.tsa.statespace.structural.UnobservedComponents.set\_stability\_method
=================================================================================
`UnobservedComponents.set_stability_method(stability_method=None, **kwargs)`
Set the numerical stability method
The Kalman filter is a recursive algorithm that may in some cases suffer issues with numerical stability. The stability method controls what, if any, measures are taken to promote stability.
| Parameters: | * **stability\_method** (*integer**,* *optional*) β Bitmask value to set the stability method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the stability method by setting individual boolean flags. See notes for details.
|
#### Notes
This method is rarely used. See the corresponding function in the `KalmanFilter` class for details.
statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.median statsmodels.sandbox.distributions.extras.SkewNorm\_gen.median
=============================================================
`SkewNorm_gen.median(*args, **kwds)`
Median of the distribution.
| Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β Location parameter, Default is 0.
* **scale** (*array\_like**,* *optional*) β Scale parameter, Default is 1.
|
| Returns: | **median** β The median of the distribution. |
| Return type: | float |
See also
`stats.distributions.rv_discrete.ppf` Inverse of the CDF
statsmodels statsmodels.nonparametric.bandwidths.select_bandwidth statsmodels.nonparametric.bandwidths.select\_bandwidth
======================================================
`statsmodels.nonparametric.bandwidths.select_bandwidth(x, bw, kernel)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/bandwidths.html#select_bandwidth)
Selects bandwidth for a selection rule bw
this is a wrapper around existing bandwidth selection rules
| Parameters: | * **x** (*array-like*) β Array for which to get the bandwidth
* **bw** (*string*) β name of bandwidth selection rule, currently supported are: normal\_reference, scott, silverman
* **kernel** (*not used yet*) β
|
| Returns: | **bw** β The estimate of the bandwidth |
| Return type: | float |
statsmodels statsmodels.robust.norms.TrimmedMean.psi statsmodels.robust.norms.TrimmedMean.psi
========================================
`TrimmedMean.psi(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#TrimmedMean.psi)
The psi function for least trimmed mean
The analytic derivative of rho
| Parameters: | **z** (*array-like*) β 1d array |
| Returns: | **psi** β psi(z) = z for |z| <= cpsi(z) = 0 for |z| > c |
| Return type: | array |
statsmodels statsmodels.discrete.discrete_model.BinaryResults.t_test statsmodels.discrete.discrete\_model.BinaryResults.t\_test
==========================================================
`BinaryResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)`
Compute a t-test for a each linear hypothesis of the form Rb = q
| Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) β
+ array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β An optional `scale` to use. Default is the scale specified by the model fit.
* **use\_t** (*bool**,* *optional*) β If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution.
|
| Returns: | **res** β The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. |
| Return type: | ContrastResults instance |
#### Examples
```
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> r = np.zeros_like(results.params)
>>> r[5:] = [1,-1]
>>> print(r)
[ 0. 0. 0. 0. 0. 1. -1.]
```
r tests that the coefficients on the 5th and 6th independent variable are the same.
```
>>> T_test = results.t_test(r)
>>> print(T_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037
==============================================================================
>>> T_test.effect
-1829.2025687192481
>>> T_test.sd
455.39079425193762
>>> T_test.tvalue
-4.0167754636411717
>>> T_test.pvalue
0.0015163772380899498
```
Alternatively, you can specify the hypothesis tests using a string
```
>>> from statsmodels.formula.api import ols
>>> dta = sm.datasets.longley.load_pandas().data
>>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR'
>>> results = ols(formula, dta).fit()
>>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1'
>>> t_test = results.t_test(hypotheses)
>>> print(t_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 15.0977 84.937 0.178 0.863 -177.042 207.238
c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915
c2 1.0001 0.249 0.000 1.000 0.437 1.563
==============================================================================
```
See also
[`tvalues`](statsmodels.discrete.discrete_model.binaryresults.tvalues#statsmodels.discrete.discrete_model.BinaryResults.tvalues "statsmodels.discrete.discrete_model.BinaryResults.tvalues")
individual t statistics
[`f_test`](statsmodels.discrete.discrete_model.binaryresults.f_test#statsmodels.discrete.discrete_model.BinaryResults.f_test "statsmodels.discrete.discrete_model.BinaryResults.f_test")
for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.t_test_pairwise statsmodels.genmod.generalized\_linear\_model.GLMResults.t\_test\_pairwise
==========================================================================
`GLMResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)`
perform pairwise t\_test with multiple testing corrected p-values
This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect.
| Parameters: | * **result** (*result instance*) β The results of an estimated model with a categorical main effect.
* **term\_name** (*str*) β name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names.
* **method** (*str* *or* *list of strings*) β multiple testing p-value correction, default is βhsβ, see stats.multipletesting
* **alpha** (*float*) β significance level for multiple testing reject decision.
* **factor\_labels** (*None**,* *list of str*) β Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used.
|
| Returns: | **results** β The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values.
* contrasts : matrix of constraints of the null hypothesis in the t\_test.
|
| Return type: | instance of a simple Results class |
#### Notes
Status: experimental. Currently only checked for treatment coding with and without specified reference level.
Currently there are no multiple testing corrected confidence intervals available.
#### Examples
```
>>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit()
>>> pw = res.t_test_pairwise("C(Weight)")
>>> pw.result_frame
coef std err t P>|t| Conf. Int. Low
2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563
3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803
3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488
Conf. Int. Upp. pvalue-hs reject-hs
2-1 1.093067 0.010212 True
3-1 1.763307 0.000002 True
3-2 1.130992 0.010212 True
```
| programming_docs |
statsmodels statsmodels.genmod.families.links.Logit.deriv2 statsmodels.genmod.families.links.Logit.deriv2
==============================================
`Logit.deriv2(p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Logit.deriv2)
Second derivative of the logit function.
| Parameters: | **p** (*array-like*) β probabilities |
| Returns: | **gββ(z)** β The value of the second derivative of the logit function |
| Return type: | array |
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.predict statsmodels.tsa.statespace.sarimax.SARIMAXResults.predict
=========================================================
`SARIMAXResults.predict(start=None, end=None, dynamic=False, **kwargs)`
In-sample prediction and out-of-sample forecasting
| Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation.
* **end** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample.
* **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) β Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead.
* **\*\*kwargs** β Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details.
|
| Returns: | **forecast** β Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k\_endog) array. |
| Return type: | array |
statsmodels statsmodels.multivariate.factor.FactorResults.uniq_stderr statsmodels.multivariate.factor.FactorResults.uniq\_stderr
==========================================================
`FactorResults.uniq_stderr(kurt=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#FactorResults.uniq_stderr)
The standard errors of the uniquenesses.
| Parameters: | **kurt** (*float*) β Excess kurtosis |
#### Notes
If excess kurtosis is known, provide as `kurt`. Standard errors are only available if the model was fit using maximum likelihood. If `endog` is not provided, `nobs` must be provided to obtain standard errors.
These are asymptotic standard errors. See Bai and Li (2012) for conditions under which the standard errors are valid.
The standard errors are only applicable to the original, unrotated maximum likelihood solution.
statsmodels statsmodels.tools.numdiff.approx_hess_cs statsmodels.tools.numdiff.approx\_hess\_cs
==========================================
`statsmodels.tools.numdiff.approx_hess_cs(x, f, epsilon=None, args=(), kwargs={})` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/numdiff.html#approx_hess_cs)
Calculate Hessian with complex-step derivative approximation Calculate Hessian with finite difference derivative approximation
| Parameters: | * **x** (*array\_like*) β value at which function derivative is evaluated
* **f** (*function*) β function of one array f(x, `*args`, `**kwargs`)
* **epsilon** (*float* *or* *array-like**,* *optional*) β Stepsize used, if None, then stepsize is automatically chosen according to EPS\*\*(1/3)\*x.
* **args** (*tuple*) β Arguments for function `f`.
* **kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) β Keyword arguments for function `f`.
|
| Returns: | **hess** β array of partial second derivatives, Hessian |
| Return type: | ndarray |
#### Notes
Equation (10) in Ridout. Computes the Hessian as:
```
1/(2*d_j*d_k) * imag(f(x + i*d[j]*e[j] + d[k]*e[k]) -
f(x + i*d[j]*e[j] - d[k]*e[k]))
```
where e[j] is a vector with element j == 1 and the rest are zero and d[i] is epsilon[i].
#### References
Ridout, M.S. (2009) Statistical applications of the complex-step method of numerical differentiation. The American Statistician, 63, 66-74
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX statsmodels.tsa.statespace.sarimax.SARIMAX
==========================================
`class statsmodels.tsa.statespace.sarimax.SARIMAX(endog, exog=None, order=(1, 0, 0), seasonal_order=(0, 0, 0, 0), trend=None, measurement_error=False, time_varying_regression=False, mle_regression=True, simple_differencing=False, enforce_stationarity=True, enforce_invertibility=True, hamilton_representation=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAX)
Seasonal AutoRegressive Integrated Moving Average with eXogenous regressors model
| Parameters: | * **endog** (*array\_like*) β The observed time-series process \(y\)
* **exog** (*array\_like**,* *optional*) β Array of exogenous regressors, shaped nobs x k.
* **order** (*iterable* *or* *iterable of iterables**,* *optional*) β The (p,d,q) order of the model for the number of AR parameters, differences, and MA parameters. `d` must be an integer indicating the integration order of the process, while `p` and `q` may either be an integers indicating the AR and MA orders (so that all lags up to those orders are included) or else iterables giving specific AR and / or MA lags to include. Default is an AR(1) model: (1,0,0).
* **seasonal\_order** (*iterable**,* *optional*) β The (P,D,Q,s) order of the seasonal component of the model for the AR parameters, differences, MA parameters, and periodicity. `d` must be an integer indicating the integration order of the process, while `p` and `q` may either be an integers indicating the AR and MA orders (so that all lags up to those orders are included) or else iterables giving specific AR and / or MA lags to include. `s` is an integer giving the periodicity (number of periods in season), often it is 4 for quarterly data or 12 for monthly data. Default is no seasonal effect.
* **trend** (*str{'n'**,**'c'**,**'t'**,**'ct'}* *or* *iterable**,* *optional*) β Parameter controlling the deterministic trend polynomial \(A(t)\). Can be specified as a string where βcβ indicates a constant (i.e. a degree zero component of the trend polynomial), βtβ indicates a linear trend with time, and βctβ is both. Can also be specified as an iterable defining the polynomial as in `numpy.poly1d`, where `[1,1,0,1]` would denote \(a + bt + ct^3\). Default is to not include a trend component.
* **measurement\_error** (*boolean**,* *optional*) β Whether or not to assume the endogenous observations `endog` were measured with error. Default is False.
* **time\_varying\_regression** (*boolean**,* *optional*) β Used when an explanatory variables, `exog`, are provided provided to select whether or not coefficients on the exogenous regressors are allowed to vary over time. Default is False.
* **mle\_regression** (*boolean**,* *optional*) β Whether or not to use estimate the regression coefficients for the exogenous variables as part of maximum likelihood estimation or through the Kalman filter (i.e. recursive least squares). If `time_varying_regression` is True, this must be set to False. Default is True.
* **simple\_differencing** (*boolean**,* *optional*) β Whether or not to use partially conditional maximum likelihood estimation. If True, differencing is performed prior to estimation, which discards the first \(s D + d\) initial rows but results in a smaller state-space formulation. If False, the full SARIMAX model is put in state-space form so that all datapoints can be used in estimation. Default is False.
* **enforce\_stationarity** (*boolean**,* *optional*) β Whether or not to transform the AR parameters to enforce stationarity in the autoregressive component of the model. Default is True.
* **enforce\_invertibility** (*boolean**,* *optional*) β Whether or not to transform the MA parameters to enforce invertibility in the moving average component of the model. Default is True.
* **hamilton\_representation** (*boolean**,* *optional*) β Whether or not to use the Hamilton representation of an ARMA process (if True) or the Harvey representation (if False). Default is False.
* **\*\*kwargs** β Keyword arguments may be used to provide default values for state space matrices or for Kalman filtering options. See `Representation`, and `KalmanFilter` for more details.
|
`measurement_error`
*boolean* β Whether or not to assume the endogenous observations `endog` were measured with error.
`state_error`
*boolean* β Whether or not the transition equation has an error component.
`mle_regression`
*boolean* β Whether or not the regression coefficients for the exogenous variables were estimated via maximum likelihood estimation.
`state_regression`
*boolean* β Whether or not the regression coefficients for the exogenous variables are included as elements of the state space and estimated via the Kalman filter.
`time_varying_regression`
*boolean* β Whether or not coefficients on the exogenous regressors are allowed to vary over time.
`simple_differencing`
*boolean* β Whether or not to use partially conditional maximum likelihood estimation.
`enforce_stationarity`
*boolean* β Whether or not to transform the AR parameters to enforce stationarity in the autoregressive component of the model.
`enforce_invertibility`
*boolean* β Whether or not to transform the MA parameters to enforce invertibility in the moving average component of the model.
`hamilton_representation`
*boolean* β Whether or not to use the Hamilton representation of an ARMA process.
`trend`
*str{βnβ,βcβ,βtβ,βctβ} or iterable* β Parameter controlling the deterministic trend polynomial \(A(t)\). See the class parameter documentation for more information.
`polynomial_ar`
*array* β Array containing autoregressive lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero).
`polynomial_ma`
*array* β Array containing moving average lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero).
`polynomial_seasonal_ar`
*array* β Array containing seasonal moving average lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero).
`polynomial_seasonal_ma`
*array* β Array containing seasonal moving average lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero).
`polynomial_trend`
*array* β Array containing trend polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero).
`k_ar`
*int* β Highest autoregressive order in the model, zero-indexed.
`k_ar_params`
*int* β Number of autoregressive parameters to be estimated.
`k_diff`
*int* β Order of intergration.
`k_ma`
*int* β Highest moving average order in the model, zero-indexed.
`k_ma_params`
*int* β Number of moving average parameters to be estimated.
`seasonal_periods`
*int* β Number of periods in a season.
`k_seasonal_ar`
*int* β Highest seasonal autoregressive order in the model, zero-indexed.
`k_seasonal_ar_params`
*int* β Number of seasonal autoregressive parameters to be estimated.
`k_seasonal_diff`
*int* β Order of seasonal intergration.
`k_seasonal_ma`
*int* β Highest seasonal moving average order in the model, zero-indexed.
`k_seasonal_ma_params`
*int* β Number of seasonal moving average parameters to be estimated.
`k_trend`
*int* β Order of the trend polynomial plus one (i.e. the constant polynomial would have `k_trend=1`).
`k_exog`
*int* β Number of exogenous regressors.
#### Notes
The SARIMA model is specified \((p, d, q) \times (P, D, Q)\_s\).
\[\phi\_p (L) \tilde \phi\_P (L^s) \Delta^d \Delta\_s^D y\_t = A(t) + \theta\_q (L) \tilde \theta\_Q (L^s) \zeta\_t\] In terms of a univariate structural model, this can be represented as
\[\begin{split}y\_t & = u\_t + \eta\_t \\ \phi\_p (L) \tilde \phi\_P (L^s) \Delta^d \Delta\_s^D u\_t & = A(t) + \theta\_q (L) \tilde \theta\_Q (L^s) \zeta\_t\end{split}\] where \(\eta\_t\) is only applicable in the case of measurement error (although it is also used in the case of a pure regression model, i.e. if p=q=0).
In terms of this model, regression with SARIMA errors can be represented easily as
\[\begin{split}y\_t & = \beta\_t x\_t + u\_t \\ \phi\_p (L) \tilde \phi\_P (L^s) \Delta^d \Delta\_s^D u\_t & = A(t) + \theta\_q (L) \tilde \theta\_Q (L^s) \zeta\_t\end{split}\] this model is the one used when exogenous regressors are provided.
Note that the reduced form lag polynomials will be written as:
\[\begin{split}\Phi (L) \equiv \phi\_p (L) \tilde \phi\_P (L^s) \\ \Theta (L) \equiv \theta\_q (L) \tilde \theta\_Q (L^s)\end{split}\] If `mle_regression` is True, regression coefficients are treated as additional parameters to be estimated via maximum likelihood. Otherwise they are included as part of the state with a diffuse initialization. In this case, however, with approximate diffuse initialization, results can be sensitive to the initial variance.
This class allows two different underlying representations of ARMA models as state space models: that of Hamilton and that of Harvey. Both are equivalent in the sense that they are analytical representations of the ARMA model, but the state vectors of each have different meanings. For this reason, maximum likelihood does not result in identical parameter estimates and even the same set of parameters will result in different loglikelihoods.
The Harvey representation is convenient because it allows integrating differencing into the state vector to allow using all observations for estimation.
In this implementation of differenced models, the Hamilton representation is not able to accomodate differencing in the state vector, so `simple_differencing` (which performs differencing prior to estimation so that the first d + sD observations are lost) must be used.
Many other packages use the Hamilton representation, so that tests against Stata and R require using it along with simple differencing (as Stata does).
Detailed information about state space models can be found in [[1]](#id2). Some specific references are:
* Chapter 3.4 describes ARMA and ARIMA models in state space form (using the Harvey representation), and gives references for basic seasonal models and models with a multiplicative form (for example the airline model). It also shows a state space model for a full ARIMA process (this is what is done here if `simple_differencing=False`).
* Chapter 3.6 describes estimating regression effects via the Kalman filter (this is performed if `mle_regression` is False), regression with time-varying coefficients, and regression with ARMA errors (recall from above that if regression effects are present, the model estimated by this class is regression with SARIMA errors).
* Chapter 8.4 describes the application of an ARMA model to an example dataset. A replication of this section is available in an example IPython notebook in the documentation.
#### References
| | |
| --- | --- |
| [[1]](#id1) | Durbin, James, and Siem Jan Koopman. 2012. Time Series Analysis by State Space Methods: Second Edition. Oxford University Press. |
#### Methods
| | |
| --- | --- |
| [`filter`](statsmodels.tsa.statespace.sarimax.sarimax.filter#statsmodels.tsa.statespace.sarimax.SARIMAX.filter "statsmodels.tsa.statespace.sarimax.SARIMAX.filter")(params[, transformed, complex\_step, β¦]) | Kalman filtering |
| [`fit`](statsmodels.tsa.statespace.sarimax.sarimax.fit#statsmodels.tsa.statespace.sarimax.SARIMAX.fit "statsmodels.tsa.statespace.sarimax.SARIMAX.fit")([start\_params, transformed, cov\_type, β¦]) | Fits the model by maximum likelihood via Kalman filter. |
| [`from_formula`](statsmodels.tsa.statespace.sarimax.sarimax.from_formula#statsmodels.tsa.statespace.sarimax.SARIMAX.from_formula "statsmodels.tsa.statespace.sarimax.SARIMAX.from_formula")(formula, data[, subset]) | Not implemented for state space models |
| [`hessian`](statsmodels.tsa.statespace.sarimax.sarimax.hessian#statsmodels.tsa.statespace.sarimax.SARIMAX.hessian "statsmodels.tsa.statespace.sarimax.SARIMAX.hessian")(params, \*args, \*\*kwargs) | Hessian matrix of the likelihood function, evaluated at the given parameters |
| [`impulse_responses`](statsmodels.tsa.statespace.sarimax.sarimax.impulse_responses#statsmodels.tsa.statespace.sarimax.SARIMAX.impulse_responses "statsmodels.tsa.statespace.sarimax.SARIMAX.impulse_responses")(params[, steps, impulse, β¦]) | Impulse response function |
| [`information`](statsmodels.tsa.statespace.sarimax.sarimax.information#statsmodels.tsa.statespace.sarimax.SARIMAX.information "statsmodels.tsa.statespace.sarimax.SARIMAX.information")(params) | Fisher information matrix of model |
| [`initialize`](statsmodels.tsa.statespace.sarimax.sarimax.initialize#statsmodels.tsa.statespace.sarimax.SARIMAX.initialize "statsmodels.tsa.statespace.sarimax.SARIMAX.initialize")() | Initialize the SARIMAX model. |
| [`initialize_approximate_diffuse`](statsmodels.tsa.statespace.sarimax.sarimax.initialize_approximate_diffuse#statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_approximate_diffuse "statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_approximate_diffuse")([variance]) | Initialize the statespace model with approximate diffuse values. |
| [`initialize_known`](statsmodels.tsa.statespace.sarimax.sarimax.initialize_known#statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_known "statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_known")(initial\_state, β¦) | Initialize the statespace model with known distribution for initial state. |
| [`initialize_state`](statsmodels.tsa.statespace.sarimax.sarimax.initialize_state#statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_state "statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_state")([variance, complex\_step]) | Initialize state and state covariance arrays in preparation for the Kalman filter. |
| [`initialize_statespace`](statsmodels.tsa.statespace.sarimax.sarimax.initialize_statespace#statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_statespace "statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_statespace")(\*\*kwargs) | Initialize the state space representation |
| [`initialize_stationary`](statsmodels.tsa.statespace.sarimax.sarimax.initialize_stationary#statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_stationary "statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_stationary")() | Initialize the statespace model as stationary. |
| [`loglike`](statsmodels.tsa.statespace.sarimax.sarimax.loglike#statsmodels.tsa.statespace.sarimax.SARIMAX.loglike "statsmodels.tsa.statespace.sarimax.SARIMAX.loglike")(params, \*args, \*\*kwargs) | Loglikelihood evaluation |
| [`loglikeobs`](statsmodels.tsa.statespace.sarimax.sarimax.loglikeobs#statsmodels.tsa.statespace.sarimax.SARIMAX.loglikeobs "statsmodels.tsa.statespace.sarimax.SARIMAX.loglikeobs")(params[, transformed, complex\_step]) | Loglikelihood evaluation |
| [`observed_information_matrix`](statsmodels.tsa.statespace.sarimax.sarimax.observed_information_matrix#statsmodels.tsa.statespace.sarimax.SARIMAX.observed_information_matrix "statsmodels.tsa.statespace.sarimax.SARIMAX.observed_information_matrix")(params[, β¦]) | Observed information matrix |
| [`opg_information_matrix`](statsmodels.tsa.statespace.sarimax.sarimax.opg_information_matrix#statsmodels.tsa.statespace.sarimax.SARIMAX.opg_information_matrix "statsmodels.tsa.statespace.sarimax.SARIMAX.opg_information_matrix")(params[, β¦]) | Outer product of gradients information matrix |
| [`predict`](statsmodels.tsa.statespace.sarimax.sarimax.predict#statsmodels.tsa.statespace.sarimax.SARIMAX.predict "statsmodels.tsa.statespace.sarimax.SARIMAX.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. |
| [`prepare_data`](statsmodels.tsa.statespace.sarimax.sarimax.prepare_data#statsmodels.tsa.statespace.sarimax.SARIMAX.prepare_data "statsmodels.tsa.statespace.sarimax.SARIMAX.prepare_data")() | Prepare data for use in the state space representation |
| [`score`](statsmodels.tsa.statespace.sarimax.sarimax.score#statsmodels.tsa.statespace.sarimax.SARIMAX.score "statsmodels.tsa.statespace.sarimax.SARIMAX.score")(params, \*args, \*\*kwargs) | Compute the score function at params. |
| [`score_obs`](statsmodels.tsa.statespace.sarimax.sarimax.score_obs#statsmodels.tsa.statespace.sarimax.SARIMAX.score_obs "statsmodels.tsa.statespace.sarimax.SARIMAX.score_obs")(params[, method, transformed, β¦]) | Compute the score per observation, evaluated at params |
| [`set_conserve_memory`](statsmodels.tsa.statespace.sarimax.sarimax.set_conserve_memory#statsmodels.tsa.statespace.sarimax.SARIMAX.set_conserve_memory "statsmodels.tsa.statespace.sarimax.SARIMAX.set_conserve_memory")([conserve\_memory]) | Set the memory conservation method |
| [`set_filter_method`](statsmodels.tsa.statespace.sarimax.sarimax.set_filter_method#statsmodels.tsa.statespace.sarimax.SARIMAX.set_filter_method "statsmodels.tsa.statespace.sarimax.SARIMAX.set_filter_method")([filter\_method]) | Set the filtering method |
| [`set_inversion_method`](statsmodels.tsa.statespace.sarimax.sarimax.set_inversion_method#statsmodels.tsa.statespace.sarimax.SARIMAX.set_inversion_method "statsmodels.tsa.statespace.sarimax.SARIMAX.set_inversion_method")([inversion\_method]) | Set the inversion method |
| [`set_smoother_output`](statsmodels.tsa.statespace.sarimax.sarimax.set_smoother_output#statsmodels.tsa.statespace.sarimax.SARIMAX.set_smoother_output "statsmodels.tsa.statespace.sarimax.SARIMAX.set_smoother_output")([smoother\_output]) | Set the smoother output |
| [`set_stability_method`](statsmodels.tsa.statespace.sarimax.sarimax.set_stability_method#statsmodels.tsa.statespace.sarimax.SARIMAX.set_stability_method "statsmodels.tsa.statespace.sarimax.SARIMAX.set_stability_method")([stability\_method]) | Set the numerical stability method |
| [`simulate`](statsmodels.tsa.statespace.sarimax.sarimax.simulate#statsmodels.tsa.statespace.sarimax.SARIMAX.simulate "statsmodels.tsa.statespace.sarimax.SARIMAX.simulate")(params, nsimulations[, β¦]) | Simulate a new time series following the state space model |
| [`simulation_smoother`](statsmodels.tsa.statespace.sarimax.sarimax.simulation_smoother#statsmodels.tsa.statespace.sarimax.SARIMAX.simulation_smoother "statsmodels.tsa.statespace.sarimax.SARIMAX.simulation_smoother")([simulation\_output]) | Retrieve a simulation smoother for the state space model. |
| [`smooth`](statsmodels.tsa.statespace.sarimax.sarimax.smooth#statsmodels.tsa.statespace.sarimax.SARIMAX.smooth "statsmodels.tsa.statespace.sarimax.SARIMAX.smooth")(params[, transformed, complex\_step, β¦]) | Kalman smoothing |
| [`transform_jacobian`](statsmodels.tsa.statespace.sarimax.sarimax.transform_jacobian#statsmodels.tsa.statespace.sarimax.SARIMAX.transform_jacobian "statsmodels.tsa.statespace.sarimax.SARIMAX.transform_jacobian")(unconstrained[, β¦]) | Jacobian matrix for the parameter transformation function |
| [`transform_params`](statsmodels.tsa.statespace.sarimax.sarimax.transform_params#statsmodels.tsa.statespace.sarimax.SARIMAX.transform_params "statsmodels.tsa.statespace.sarimax.SARIMAX.transform_params")(unconstrained) | Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation. |
| [`untransform_params`](statsmodels.tsa.statespace.sarimax.sarimax.untransform_params#statsmodels.tsa.statespace.sarimax.SARIMAX.untransform_params "statsmodels.tsa.statespace.sarimax.SARIMAX.untransform_params")(constrained) | Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer |
| [`update`](statsmodels.tsa.statespace.sarimax.sarimax.update#statsmodels.tsa.statespace.sarimax.SARIMAX.update "statsmodels.tsa.statespace.sarimax.SARIMAX.update")(params[, transformed, complex\_step]) | Update the parameters of the model |
#### Attributes
| | |
| --- | --- |
| `endog_names` | Names of endogenous variables |
| `exog_names` | |
| `initial_design` | Initial design matrix |
| `initial_selection` | Initial selection matrix |
| `initial_state_intercept` | Initial state intercept vector |
| `initial_transition` | Initial transition matrix |
| `initial_variance` | |
| `initialization` | |
| `loglikelihood_burn` | |
| `model_latex_names` | The latex names of all possible model parameters. |
| `model_names` | The plain text names of all possible model parameters. |
| `model_orders` | The orders of each of the polynomials in the model. |
| `param_names` | List of human readable parameter names (for parameters actually included in the model). |
| `param_terms` | List of parameters actually included in the model, in sorted order. |
| `params_complete` | |
| `start_params` | Starting parameters for maximum likelihood estimation |
| `tolerance` | |
| programming_docs |
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.remove_data statsmodels.tsa.statespace.sarimax.SARIMAXResults.remove\_data
==============================================================
`SARIMAXResults.remove_data()`
remove data arrays, all nobs arrays from result and model
This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.
Warning
Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.
Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.
The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data.
The attributes to remove are named in:
`model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name.
`result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name)
`result._data_attr_model : arrays attached to the model` instance but not to the results instance
statsmodels statsmodels.regression.quantile_regression.QuantRegResults.rsquared statsmodels.regression.quantile\_regression.QuantRegResults.rsquared
====================================================================
`QuantRegResults.rsquared()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.rsquared)
statsmodels statsmodels.regression.quantile_regression.QuantReg.initialize statsmodels.regression.quantile\_regression.QuantReg.initialize
===============================================================
`QuantReg.initialize()`
Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed.
statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.fit
==============================================================
`BinomialBayesMixedGLM.fit()`
Fit a model to data.
statsmodels statsmodels.discrete.discrete_model.Probit.predict statsmodels.discrete.discrete\_model.Probit.predict
===================================================
`Probit.predict(params, exog=None, linear=False)`
Predict response variable of a model given exogenous variables.
| Parameters: | * **params** (*array-like*) β Fitted parameters of the model.
* **exog** (*array-like*) β 1d or 2d array of exogenous values. If not supplied, the whole exog attribute of the model is used.
* **linear** (*bool**,* *optional*) β If True, returns the linear predictor dot(exog,params). Else, returns the value of the cdf at the linear predictor.
|
| Returns: | Fitted values at exog. |
| Return type: | array |
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.set_conserve_memory statsmodels.tsa.statespace.sarimax.SARIMAX.set\_conserve\_memory
================================================================
`SARIMAX.set_conserve_memory(conserve_memory=None, **kwargs)`
Set the memory conservation method
By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored.
| Parameters: | * **conserve\_memory** (*integer**,* *optional*) β Bitmask value to set the memory conservation method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags.
|
#### Notes
This method is rarely used. See the corresponding function in the `KalmanFilter` class for details.
statsmodels statsmodels.regression.recursive_ls.RecursiveLS.set_stability_method statsmodels.regression.recursive\_ls.RecursiveLS.set\_stability\_method
=======================================================================
`RecursiveLS.set_stability_method(stability_method=None, **kwargs)`
Set the numerical stability method
The Kalman filter is a recursive algorithm that may in some cases suffer issues with numerical stability. The stability method controls what, if any, measures are taken to promote stability.
| Parameters: | * **stability\_method** (*integer**,* *optional*) β Bitmask value to set the stability method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the stability method by setting individual boolean flags. See notes for details.
|
#### Notes
This method is rarely used. See the corresponding function in the `KalmanFilter` class for details.
statsmodels statsmodels.discrete.discrete_model.LogitResults.conf_int statsmodels.discrete.discrete\_model.LogitResults.conf\_int
===========================================================
`LogitResults.conf_int(alpha=0.05, cols=None, method='default')`
Returns the confidence interval of the fitted parameters.
| Parameters: | * **alpha** (*float**,* *optional*) β The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval.
* **cols** (*array-like**,* *optional*) β `cols` specifies which confidence intervals to return
* **method** (*string*) β Not Implemented Yet Method to estimate the confidence\_interval. βDefaultβ : uses self.bse which is based on inverse Hessian for MLE βhjjhβ : βjacβ : βboot-bseβ βboot\_quantβ βprofileβ
|
| Returns: | **conf\_int** β Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. |
| Return type: | array |
#### Examples
```
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> results.conf_int()
array([[-5496529.48322745, -1467987.78596704],
[ -177.02903529, 207.15277984],
[ -0.1115811 , 0.03994274],
[ -3.12506664, -0.91539297],
[ -1.5179487 , -0.54850503],
[ -0.56251721, 0.460309 ],
[ 798.7875153 , 2859.51541392]])
```
```
>>> results.conf_int(cols=(2,3))
array([[-0.1115811 , 0.03994274],
[-3.12506664, -0.91539297]])
```
#### Notes
The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method.
statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.ma_rep statsmodels.tsa.vector\_ar.var\_model.VARProcess.ma\_rep
========================================================
`VARProcess.ma_rep(maxn=10)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.ma_rep)
Compute MA(\(\infty\)) coefficient matrices
| Parameters: | **maxn** (*int*) β Number of coefficient matrices to compute |
| Returns: | **coefs** |
| Return type: | ndarray (maxn x k x k) |
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.resid statsmodels.genmod.generalized\_estimating\_equations.GEEResults.resid
======================================================================
`GEEResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid)
Returns the residuals, the endogeneous data minus the fitted values from the model.
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.get_margeff statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.get\_margeff
=========================================================================
`ZeroInflatedPoissonResults.get_margeff(at='overall', method='dydx', atexog=None, dummy=False, count=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#ZeroInflatedPoissonResults.get_margeff)
Get marginal effects of the fitted model.
Not yet implemented for Zero Inflated Models
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.set_conserve_memory statsmodels.tsa.statespace.structural.UnobservedComponents.set\_conserve\_memory
================================================================================
`UnobservedComponents.set_conserve_memory(conserve_memory=None, **kwargs)`
Set the memory conservation method
By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored.
| Parameters: | * **conserve\_memory** (*integer**,* *optional*) β Bitmask value to set the memory conservation method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags.
|
#### Notes
This method is rarely used. See the corresponding function in the `KalmanFilter` class for details.
statsmodels statsmodels.sandbox.regression.try_catdata.convertlabels statsmodels.sandbox.regression.try\_catdata.convertlabels
=========================================================
`statsmodels.sandbox.regression.try_catdata.convertlabels(ys, indices=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_catdata.html#convertlabels)
convert labels based on multiple variables or string labels to unique index labels 0,1,2,β¦,nk-1 where nk is the number of distinct labels
statsmodels statsmodels.tsa.statespace.varmax.VARMAX.score_obs statsmodels.tsa.statespace.varmax.VARMAX.score\_obs
===================================================
`VARMAX.score_obs(params, method='approx', transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)`
Compute the score per observation, evaluated at params
| Parameters: | * **params** (*array\_like*) β Array of parameters at which to evaluate the score.
* **kwargs** β Additional arguments to the `loglike` method.
|
| Returns: | **score** β Score per observation, evaluated at `params`. |
| Return type: | array |
#### Notes
This is a numerical approximation, calculated using first-order complex step differentiation on the `loglikeobs` method.
statsmodels statsmodels.sandbox.stats.multicomp.MultiComparison.tukeyhsd statsmodels.sandbox.stats.multicomp.MultiComparison.tukeyhsd
============================================================
`MultiComparison.tukeyhsd(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#MultiComparison.tukeyhsd)
Tukeyβs range test to compare means of all pairs of groups
| Parameters: | **alpha** (*float**,* *optional*) β Value of FWER at which to calculate HSD. |
| Returns: | **results** β A results class containing relevant data and some post-hoc calculations |
| Return type: | TukeyHSDResults instance |
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.bse statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.bse
===========================================================================
`ZeroInflatedGeneralizedPoissonResults.bse()`
statsmodels statsmodels.miscmodels.count.PoissonGMLE.nloglike statsmodels.miscmodels.count.PoissonGMLE.nloglike
=================================================
`PoissonGMLE.nloglike(params)`
statsmodels statsmodels.genmod.families.family.InverseGaussian.deviance statsmodels.genmod.families.family.InverseGaussian.deviance
===========================================================
`InverseGaussian.deviance(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)`
The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution.
Deviance is usually defined as twice the loglikelihood ratio.
| Parameters: | * **endog** (*array-like*) β The endogenous response variable
* **mu** (*array-like*) β The inverse of the link function at the linear predicted values.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **freq\_weights** (*array-like*) β 1d array of frequency weights. The default is 1.
* **scale** (*float**,* *optional*) β An optional scale argument. The default is 1.
|
| Returns: | **Deviance** β The value of deviance function defined below. |
| Return type: | array |
#### Notes
Deviance is defined
\[D = 2\sum\_i (freq\\_weights\_i \* var\\_weights \* (llf(endog\_i, endog\_i) - llf(endog\_i, \mu\_i)))\] where y is the endogenous variable. The deviance functions are analytically defined for each family.
Internally, we calculate deviance as:
\[D = \sum\_i freq\\_weights\_i \* var\\_weights \* resid\\_dev\_i / scale\]
statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.bic statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.bic
==================================================================
`GeneralizedPoissonResults.bic()`
statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.moment statsmodels.sandbox.distributions.extras.NormExpan\_gen.moment
==============================================================
`NormExpan_gen.moment(n, *args, **kwds)`
n-th order non-central moment of distribution.
| Parameters: | * **n** (*int**,* *n >= 1*) β Order of moment.
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information).
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.nnlf statsmodels.sandbox.distributions.transformed.Transf\_gen.nnlf
==============================================================
`Transf_gen.nnlf(theta, x)`
Return negative loglikelihood function.
#### Notes
This is `-sum(log pdf(x, theta), axis=0)` where `theta` are the parameters (including loc and scale).
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.test_serial_correlation statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.test\_serial\_correlation
=========================================================================================
`DynamicFactorResults.test_serial_correlation(method, lags=None)`
Ljung-box test for no serial correlation of standardized residuals
Null hypothesis is no serial correlation.
| Parameters: | * **method** (*string {'ljungbox'**,**'boxpierece'}* *or* *None*) β The statistical test for serial correlation. If None, an attempt is made to select an appropriate test.
* **lags** (*None**,* *int* *or* *array\_like*) β If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is 12\*(nobs/100)^{1/4}
|
| Returns: | **output** β An array with `(test_statistic, pvalue)` for each endogenous variable and each lag. The array is then sized `(k_endog, 2, lags)`. If the method is called as `ljungbox = res.test_serial_correlation()`, then `ljungbox[i]` holds the results of the Ljung-Box test (as would be returned by `statsmodels.stats.diagnostic.acorr_ljungbox`) for the `i` th endogenous variable. |
| Return type: | array |
#### Notes
If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals.
Output is nan for any endogenous variable which has missing values.
See also
[`statsmodels.stats.diagnostic.acorr_ljungbox`](statsmodels.stats.diagnostic.acorr_ljungbox#statsmodels.stats.diagnostic.acorr_ljungbox "statsmodels.stats.diagnostic.acorr_ljungbox")
statsmodels statsmodels.discrete.discrete_model.ProbitResults.llr_pvalue statsmodels.discrete.discrete\_model.ProbitResults.llr\_pvalue
==============================================================
`ProbitResults.llr_pvalue()`
statsmodels statsmodels.stats.diagnostic.het_goldfeldquandt statsmodels.stats.diagnostic.het\_goldfeldquandt
================================================
`statsmodels.stats.diagnostic.het_goldfeldquandt = <statsmodels.sandbox.stats.diagnostic.HetGoldfeldQuandt object>`
see class docstring
statsmodels statsmodels.tsa.statespace.kalman_smoother.SmootherResults statsmodels.tsa.statespace.kalman\_smoother.SmootherResults
===========================================================
`class statsmodels.tsa.statespace.kalman_smoother.SmootherResults(model)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_smoother.html#SmootherResults)
Results from applying the Kalman smoother and/or filter to a state space model.
| Parameters: | **model** ([Representation](statsmodels.tsa.statespace.representation.representation#statsmodels.tsa.statespace.representation.Representation "statsmodels.tsa.statespace.representation.Representation")) β A Statespace representation |
`nobs`
*int* β Number of observations.
`k_endog`
*int* β The dimension of the observation series.
`k_states`
*int* β The dimension of the unobserved state process.
`k_posdef`
*int* β The dimension of a guaranteed positive definite covariance matrix describing the shocks in the measurement equation.
`dtype`
*dtype* β Datatype of representation matrices
`prefix`
*str* β BLAS prefix of representation matrices
`shapes`
*dictionary of name:tuple* β A dictionary recording the shapes of each of the representation matrices as tuples.
`endog`
*array* β The observation vector.
`design`
*array* β The design matrix, \(Z\).
`obs_intercept`
*array* β The intercept for the observation equation, \(d\).
`obs_cov`
*array* β The covariance matrix for the observation equation \(H\).
`transition`
*array* β The transition matrix, \(T\).
`state_intercept`
*array* β The intercept for the transition equation, \(c\).
`selection`
*array* β The selection matrix, \(R\).
`state_cov`
*array* β The covariance matrix for the state equation \(Q\).
`missing`
*array of bool* β An array of the same size as `endog`, filled with boolean values that are True if the corresponding entry in `endog` is NaN and False otherwise.
`nmissing`
*array of int* β An array of size `nobs`, where the ith entry is the number (between 0 and k\_endog) of NaNs in the ith row of the `endog` array.
`time_invariant`
*bool* β Whether or not the representation matrices are time-invariant
`initialization`
*str* β Kalman filter initialization method.
`initial_state`
*array\_like* β The state vector used to initialize the Kalamn filter.
`initial_state_cov`
*array\_like* β The state covariance matrix used to initialize the Kalamn filter.
`filter_method`
*int* β Bitmask representing the Kalman filtering method
`inversion_method`
*int* β Bitmask representing the method used to invert the forecast error covariance matrix.
`stability_method`
*int* β Bitmask representing the methods used to promote numerical stability in the Kalman filter recursions.
`conserve_memory`
*int* β Bitmask representing the selected memory conservation method.
`tolerance`
*float* β The tolerance at which the Kalman filter determines convergence to steady-state.
`loglikelihood_burn`
*int* β The number of initial periods during which the loglikelihood is not recorded.
`converged`
*bool* β Whether or not the Kalman filter converged.
`period_converged`
*int* β The time period in which the Kalman filter converged.
`filtered_state`
*array* β The filtered state vector at each time period.
`filtered_state_cov`
*array* β The filtered state covariance matrix at each time period.
`predicted_state`
*array* β The predicted state vector at each time period.
`predicted_state_cov`
*array* β The predicted state covariance matrix at each time period.
`kalman_gain`
*array* β The Kalman gain at each time period.
`forecasts`
*array* β The one-step-ahead forecasts of observations at each time period.
`forecasts_error`
*array* β The forecast errors at each time period.
`forecasts_error_cov`
*array* β The forecast error covariance matrices at each time period.
`loglikelihood`
*array* β The loglikelihood values at each time period.
`collapsed_forecasts`
*array* β If filtering using collapsed observations, stores the one-step-ahead forecasts of collapsed observations at each time period.
`collapsed_forecasts_error`
*array* β If filtering using collapsed observations, stores the one-step-ahead forecast errors of collapsed observations at each time period.
`collapsed_forecasts_error_cov`
*array* β If filtering using collapsed observations, stores the one-step-ahead forecast error covariance matrices of collapsed observations at each time period.
`standardized_forecast_error`
*array* β The standardized forecast errors
`smoother_output`
*int* β Bitmask representing the generated Kalman smoothing output
`scaled_smoothed_estimator`
*array* β The scaled smoothed estimator at each time period.
`scaled_smoothed_estimator_cov`
*array* β The scaled smoothed estimator covariance matrices at each time period.
`smoothing_error`
*array* β The smoothing error covariance matrices at each time period.
`smoothed_state`
*array* β The smoothed state at each time period.
`smoothed_state_cov`
*array* β The smoothed state covariance matrices at each time period.
`smoothed_state_autocov`
*array* β The smoothed state lago-one autocovariance matrices at each time period: \(Cov(\alpha\_{t+1}, \alpha\_t)\).
`smoothed_measurement_disturbance`
*array* β The smoothed measurement at each time period.
`smoothed_state_disturbance`
*array* β The smoothed state at each time period.
`smoothed_measurement_disturbance_cov`
*array* β The smoothed measurement disturbance covariance matrices at each time period.
`smoothed_state_disturbance_cov`
*array* β The smoothed state disturbance covariance matrices at each time period.
#### Methods
| | |
| --- | --- |
| [`predict`](statsmodels.tsa.statespace.kalman_smoother.smootherresults.predict#statsmodels.tsa.statespace.kalman_smoother.SmootherResults.predict "statsmodels.tsa.statespace.kalman_smoother.SmootherResults.predict")([start, end, dynamic]) | In-sample and out-of-sample prediction for state space models generally |
| [`update_filter`](statsmodels.tsa.statespace.kalman_smoother.smootherresults.update_filter#statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_filter "statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_filter")(kalman\_filter) | Update the filter results |
| [`update_representation`](statsmodels.tsa.statespace.kalman_smoother.smootherresults.update_representation#statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_representation "statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_representation")(model[, only\_options]) | Update the results to match a given model |
| [`update_smoother`](statsmodels.tsa.statespace.kalman_smoother.smootherresults.update_smoother#statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_smoother "statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_smoother")(smoother) | Update the smoother results |
#### Attributes
| | |
| --- | --- |
| [`kalman_gain`](#statsmodels.tsa.statespace.kalman_smoother.SmootherResults.kalman_gain "statsmodels.tsa.statespace.kalman_smoother.SmootherResults.kalman_gain") | Kalman gain matrices |
| `smoothed_forecasts` | |
| `smoothed_forecasts_error` | |
| `smoothed_forecasts_error_cov` | |
| `standardized_forecasts_error` | Standardized forecast errors |
| programming_docs |
statsmodels statsmodels.regression.linear_model.OLSResults.condition_number statsmodels.regression.linear\_model.OLSResults.condition\_number
=================================================================
`OLSResults.condition_number()`
Return condition number of exogenous matrix.
Calculated as ratio of largest to smallest eigenvalue.
statsmodels statsmodels.stats.contingency_tables.Table2x2.homogeneity statsmodels.stats.contingency\_tables.Table2x2.homogeneity
==========================================================
`Table2x2.homogeneity(method='stuart_maxwell')`
Compare row and column marginal distributions.
| Parameters: | * **method** (*string*) β Either βstuart\_maxwellβ or βbhapkarβ, leading to two different estimates of the covariance matrix for the estimated difference between the row margins and the column margins.
* **a bunch with attributes** (*Returns*) β
* **statistic** (*float*) β The chi^2 test statistic
* **pvalue** (*float*) β The p-value of the test statistic
* **df** (*integer*) β The degrees of freedom of the reference distribution
|
#### Notes
For a 2x2 table this is equivalent to McNemarβs test. More generally the procedure tests the null hypothesis that the marginal distribution of the row factor is equal to the marginal distribution of the column factor. For this to be meaningful, the two factors must have the same sample space (i.e. the same categories).
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.wald_test statsmodels.genmod.generalized\_estimating\_equations.GEEResults.wald\_test
===========================================================================
`GEEResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)`
Compute a Wald-test for a joint linear hypothesis.
| Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) β
+ array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β Default is 1.0 for no scaling.
* **invcov** (*array-like**,* *optional*) β A q x q array to specify an inverse covariance matrix based on a restrictions matrix.
* **use\_f** (*bool*) β If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis.
|
| Returns: | **res** β The results for the test are attributes of this results instance. |
| Return type: | ContrastResults instance |
See also
[`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.genmod.generalized_estimating_equations.geeresults.f_test#statsmodels.genmod.generalized_estimating_equations.GEEResults.f_test "statsmodels.genmod.generalized_estimating_equations.GEEResults.f_test"), [`t_test`](statsmodels.genmod.generalized_estimating_equations.geeresults.t_test#statsmodels.genmod.generalized_estimating_equations.GEEResults.t_test "statsmodels.genmod.generalized_estimating_equations.GEEResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
#### Notes
The matrix `r_matrix` is assumed to be non-singular. More precisely,
r\_matrix (pX pX.T) r\_matrix.T
is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.zvalues statsmodels.tsa.statespace.varmax.VARMAXResults.zvalues
=======================================================
`VARMAXResults.zvalues()`
(array) The z-statistics for the coefficients.
statsmodels statsmodels.genmod.families.links.Power.deriv statsmodels.genmod.families.links.Power.deriv
=============================================
`Power.deriv(p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Power.deriv)
Derivative of the power transform
| Parameters: | **p** (*array-like*) β Mean parameters |
| Returns: | **gβ(p)** β Derivative of power transform of `p` |
| Return type: | array |
#### Notes
gβ(`p`) = `power` \* `p`**(`power` - 1)
statsmodels statsmodels.discrete.discrete_model.BinaryResults.cov_params statsmodels.discrete.discrete\_model.BinaryResults.cov\_params
==============================================================
`BinaryResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)`
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar.
| Parameters: | * **r\_matrix** (*array-like*) β Can be 1d, or 2d. Can be used alone or with other.
* **column** (*array-like**,* *optional*) β Must be used on its own. Can be 0d or 1d see below.
* **scale** (*float**,* *optional*) β Can be specified or not. Default is None, which means that the scale argument is taken from the model.
* **other** (*array-like**,* *optional*) β Can be used when r\_matrix is specified.
|
| Returns: | **cov** β covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. |
| Return type: | ndarray |
#### Notes
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)`
If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T`
If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T`
If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d
OR
`(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d
statsmodels statsmodels.stats.outliers_influence.OLSInfluence.resid_studentized_external statsmodels.stats.outliers\_influence.OLSInfluence.resid\_studentized\_external
===============================================================================
`OLSInfluence.resid_studentized_external()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.resid_studentized_external)
(cached attribute) studentized residuals using LOOO variance
this uses sigma from leave-one-out estimates
requires leave one out loop for observations
statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian_factor statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian\_factor
==============================================================
`PoissonOffsetGMLE.hessian_factor(params, scale=None, observed=True)`
Weights for calculating Hessian
| Parameters: | * **params** (*ndarray*) β parameter at which Hessian is evaluated
* **scale** (*None* *or* *float*) β If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale.
* **observed** (*bool*) β If True, then the observed Hessian is returned. If false then the expected information matrix is returned.
|
| Returns: | **hessian\_factor** β A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` |
| Return type: | ndarray, 1d |
statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.bind statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.bind
===============================================================
`KalmanSmoother.bind(endog)`
Bind data to the statespace representation
| Parameters: | **endog** (*array*) β Endogenous data to bind to the model. Must be column-ordered ndarray with shape (`k_endog`, `nobs`) or row-ordered ndarray with shape (`nobs`, `k_endog`). |
#### Notes
The strict requirements arise because the underlying statespace and Kalman filtering classes require Fortran-ordered arrays in the wide format (shaped (`k_endog`, `nobs`)), and this structure is setup to prevent copying arrays in memory.
By default, numpy arrays are row (C)-ordered and most time series are represented in the long format (with time on the 0-th axis). In this case, no copying or re-ordering needs to be performed, instead the array can simply be transposed to get it in the right order and shape.
Although this class (Representation) has stringent `bind` requirements, it is assumed that it will rarely be used directly.
statsmodels statsmodels.regression.linear_model.GLSAR.fit statsmodels.regression.linear\_model.GLSAR.fit
==============================================
`GLSAR.fit(method='pinv', cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)`
Full fit of the model.
The results include an estimate of covariance matrix, (whitened) residuals and an estimate of scale.
| Parameters: | * **method** (*str**,* *optional*) β Can be βpinvβ, βqrβ. βpinvβ uses the Moore-Penrose pseudoinverse to solve the least squares problem. βqrβ uses the QR factorization.
* **cov\_type** (*str**,* *optional*) β See `regression.linear_model.RegressionResults` for a description of the available covariance estimators
* **cov\_kwds** (*list* *or* *None**,* *optional*) β See `linear_model.RegressionResults.get_robustcov_results` for a description required keywords for alternative covariance estimators
* **use\_t** (*bool**,* *optional*) β Flag indicating to use the Studentβs t distribution when computing p-values. Default behavior depends on cov\_type. See `linear_model.RegressionResults.get_robustcov_results` for implementation details.
|
| Returns: | |
| Return type: | A RegressionResults class instance. |
See also
`regression.linear_model.RegressionResults`, `regression.linear_model.RegressionResults.get_robustcov_results`
#### Notes
The fit method uses the pseudoinverse of the design/exogenous variables to solve the least squares minimization.
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.forecast_interval statsmodels.tsa.vector\_ar.var\_model.VARResults.forecast\_interval
===================================================================
`VARResults.forecast_interval(y, steps, alpha=0.05, exog_future=None)`
Construct forecast interval estimates assuming the y are Gaussian
#### Notes
LΓΌtkepohl pp. 39-40
| Returns: | **(mid, lower, upper)** |
| Return type: | (ndarray, ndarray, ndarray) |
statsmodels statsmodels.genmod.families.family.Poisson.loglike_obs statsmodels.genmod.families.family.Poisson.loglike\_obs
=======================================================
`Poisson.loglike_obs(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Poisson.loglike_obs)
The log-likelihood function for each observation in terms of the fitted mean response for the Poisson distribution.
| Parameters: | * **endog** (*array*) β Usually the endogenous response variable.
* **mu** (*array*) β Usually but not always the fitted mean response variable.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **scale** (*float*) β The scale parameter. The default is 1.
|
| Returns: | **ll\_i** β The value of the loglikelihood evaluated at (endog, mu, var\_weights, scale) as defined below. |
| Return type: | float |
#### Notes
\[ll\_i = var\\_weights\_i / scale \* (endog\_i \* \ln(\mu\_i) - \mu\_i - \ln \Gamma(endog\_i + 1))\]
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.impulse_responses statsmodels.regression.recursive\_ls.RecursiveLSResults.impulse\_responses
==========================================================================
`RecursiveLSResults.impulse_responses(steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs)`
Impulse response function
| Parameters: | * **steps** (*int**,* *optional*) β The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries.
* **impulse** (*int* *or* *array\_like*) β If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`.
* **orthogonalized** (*boolean**,* *optional*) β Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False.
* **cumulative** (*boolean**,* *optional*) β Whether or not to return cumulative impulse responses. Default is False.
* **\*\*kwargs** β If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values.
|
| Returns: | **impulse\_responses** β Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k\_endog) array. |
| Return type: | array |
#### Notes
Intercepts in the measurement and state equation are ignored when calculating impulse responses.
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.bse statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.bse
===================================================================
`DynamicFactorResults.bse()`
statsmodels statsmodels.emplike.descriptive.DescStatMV.ci_corr statsmodels.emplike.descriptive.DescStatMV.ci\_corr
===================================================
`DescStatMV.ci_corr(sig=0.05, upper_bound=None, lower_bound=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatMV.ci_corr)
Returns the confidence intervals for the correlation coefficient
| Parameters: | * **sig** (*float*) β The significance level. Default is .05
* **upper\_bound** (*float*) β Maximum value the upper confidence limit can be. Default is 99% confidence limit assuming normality.
* **lower\_bound** (*float*) β Minimum value the lower condidence limit can be. Default is 99% confidence limit assuming normality.
|
| Returns: | **interval** β Confidence interval for the correlation |
| Return type: | tuple |
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.resid_recursive statsmodels.regression.recursive\_ls.RecursiveLSResults.resid\_recursive
========================================================================
`RecursiveLSResults.resid_recursive()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLSResults.resid_recursive)
Recursive residuals
| Returns: | **resid\_recursive** β An array of length `nobs` holding the recursive residuals. |
| Return type: | array\_like |
#### Notes
The first `k_exog` residuals are typically unreliable due to initialization.
statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_oim statsmodels.tsa.statespace.varmax.VARMAXResults.cov\_params\_oim
================================================================
`VARMAXResults.cov_params_oim()`
(array) The variance / covariance matrix. Computed using the method from Harvey (1989).
statsmodels statsmodels.tsa.stattools.levinson_durbin statsmodels.tsa.stattools.levinson\_durbin
==========================================
`statsmodels.tsa.stattools.levinson_durbin(s, nlags=10, isacov=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#levinson_durbin)
Levinson-Durbin recursion for autoregressive processes
| Parameters: | * **s** (*array\_like*) β If isacov is False, then this is the time series. If iasacov is true then this is interpreted as autocovariance starting with lag 0
* **nlags** (*integer*) β largest lag to include in recursion or order of the autoregressive process
* **isacov** (*boolean*) β flag to indicate whether the first argument, s, contains the autocovariances or the data series.
|
| Returns: | * **sigma\_v** (*float*) β estimate of the error variance ?
* **arcoefs** (*ndarray*) β estimate of the autoregressive coefficients
* **pacf** (*ndarray*) β partial autocorrelation function
* **sigma** (*ndarray*) β entire sigma array from intermediate result, last value is sigma\_v
* **phi** (*ndarray*) β entire phi array from intermediate result, last column contains autoregressive coefficients for AR(nlags) with a leading 1
|
#### Notes
This function returns currently all results, but maybe we drop sigma and phi from the returns.
If this function is called with the time series (isacov=False), then the sample autocovariance function is calculated with the default options (biased, no fft).
statsmodels statsmodels.regression.quantile_regression.QuantRegResults.HC1_se statsmodels.regression.quantile\_regression.QuantRegResults.HC1\_se
===================================================================
`QuantRegResults.HC1_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.HC1_se)
See statsmodels.RegressionResults
statsmodels statsmodels.regression.linear_model.OLSResults.uncentered_tss statsmodels.regression.linear\_model.OLSResults.uncentered\_tss
===============================================================
`OLSResults.uncentered_tss()`
statsmodels statsmodels.robust.robust_linear_model.RLMResults.t_test_pairwise statsmodels.robust.robust\_linear\_model.RLMResults.t\_test\_pairwise
=====================================================================
`RLMResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)`
perform pairwise t\_test with multiple testing corrected p-values
This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect.
| Parameters: | * **result** (*result instance*) β The results of an estimated model with a categorical main effect.
* **term\_name** (*str*) β name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names.
* **method** (*str* *or* *list of strings*) β multiple testing p-value correction, default is βhsβ, see stats.multipletesting
* **alpha** (*float*) β significance level for multiple testing reject decision.
* **factor\_labels** (*None**,* *list of str*) β Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used.
|
| Returns: | **results** β The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values.
* contrasts : matrix of constraints of the null hypothesis in the t\_test.
|
| Return type: | instance of a simple Results class |
#### Notes
Status: experimental. Currently only checked for treatment coding with and without specified reference level.
Currently there are no multiple testing corrected confidence intervals available.
#### Examples
```
>>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit()
>>> pw = res.t_test_pairwise("C(Weight)")
>>> pw.result_frame
coef std err t P>|t| Conf. Int. Low
2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563
3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803
3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488
Conf. Int. Upp. pvalue-hs reject-hs
2-1 1.093067 0.010212 True
3-1 1.763307 0.000002 True
3-2 1.130992 0.010212 True
```
| programming_docs |
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.resid statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.resid
=============================================================================
`ZeroInflatedGeneralizedPoissonResults.resid()`
Residuals
#### Notes
The residuals for Count models are defined as
\[y - p\] where \(p = \exp(X\beta)\). Any exposure and offset variables are also handled.
statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.load statsmodels.tsa.statespace.varmax.VARMAXResults.load
====================================================
`classmethod VARMAXResults.load(fname)`
load a pickle, (class method)
| Parameters: | **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle. |
| Returns: | |
| Return type: | unpickled instance |
statsmodels statsmodels.robust.norms.HuberT statsmodels.robust.norms.HuberT
===============================
`class statsmodels.robust.norms.HuberT(t=1.345)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#HuberT)
Huberβs T for M estimation.
| Parameters: | **t** (*float**,* *optional*) β The tuning constant for Huberβs t function. The default value is 1.345. |
See also
[`statsmodels.robust.norms.RobustNorm`](statsmodels.robust.norms.robustnorm#statsmodels.robust.norms.RobustNorm "statsmodels.robust.norms.RobustNorm")
#### Methods
| | |
| --- | --- |
| [`psi`](statsmodels.robust.norms.hubert.psi#statsmodels.robust.norms.HuberT.psi "statsmodels.robust.norms.HuberT.psi")(z) | The psi function for Huberβs t estimator |
| [`psi_deriv`](statsmodels.robust.norms.hubert.psi_deriv#statsmodels.robust.norms.HuberT.psi_deriv "statsmodels.robust.norms.HuberT.psi_deriv")(z) | The derivative of Huberβs t psi function |
| [`rho`](statsmodels.robust.norms.hubert.rho#statsmodels.robust.norms.HuberT.rho "statsmodels.robust.norms.HuberT.rho")(z) | The robust criterion function for Huberβs t. |
| [`weights`](statsmodels.robust.norms.hubert.weights#statsmodels.robust.norms.HuberT.weights "statsmodels.robust.norms.HuberT.weights")(z) | Huberβs t weighting function for the IRLS algorithm |
statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.tvalues statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.tvalues
=============================================================================
`ZeroInflatedNegativeBinomialResults.tvalues()`
Return the t-statistic for a given parameter estimate.
statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.wald_test_terms statsmodels.tsa.statespace.varmax.VARMAXResults.wald\_test\_terms
=================================================================
`VARMAXResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)`
Compute a sequence of Wald tests for terms over multiple columns
This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero.
`Terms` are defined by the underlying formula or by string matching.
| Parameters: | * **skip\_single** (*boolean*) β If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included.
* **extra\_constraints** (*ndarray*) β not tested yet
* **combine\_terms** (*None* *or* *list of strings*) β Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test.
|
| Returns: | **test\_result** β The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. |
| Return type: | result instance |
#### Examples
```
>>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit()
>>> res_ols.wald_test_terms()
<class 'statsmodels.stats.contrast.WaldTestResults'>
F P>F df constraint df denom
Intercept 279.754525 2.37985521351e-22 1 51
C(Duration, Sum) 5.367071 0.0245738436636 1 51
C(Weight, Sum) 12.432445 3.99943118767e-05 2 51
C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51
```
```
>>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0')
>>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight'])
>>> print(wt)
chi2 P>chi2 df constraint
Intercept 15.695625 7.43960374424e-05 1
C(Weight) 16.132616 0.000313940174705 2
C(Duration) 1.009147 0.315107378931 1
C(Weight):C(Duration) 0.216694 0.897315972824 2
Duration 11.187849 0.010752286833 3
Weight 30.263368 4.32586407145e-06 4
```
statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.regime_transition_matrix statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.regime\_transition\_matrix
================================================================================================
`MarkovRegression.regime_transition_matrix(params, exog_tvtp=None)`
Construct the left-stochastic transition matrix
#### Notes
This matrix will either be shaped (k\_regimes, k\_regimes, 1) or if there are time-varying transition probabilities, it will be shaped (k\_regimes, k\_regimes, nobs).
The (i,j)th element of this matrix is the probability of transitioning from regime j to regime i; thus the previous regime is represented in a column and the next regime is represented by a row.
It is left-stochastic, meaning that each column sums to one (because it is certain that from one regime (j) you will transition to *some other regime*).
statsmodels statsmodels.tsa.vector_ar.var_model.VAR.from_formula statsmodels.tsa.vector\_ar.var\_model.VAR.from\_formula
=======================================================
`classmethod VAR.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)`
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.f_test statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.f\_test
====================================================================
`ZeroInflatedPoissonResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)`
Compute the F-test for a joint linear hypothesis.
This is a special case of `wald_test` that always uses the F distribution.
| Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) β
+ array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β Default is 1.0 for no scaling.
* **invcov** (*array-like**,* *optional*) β A q x q array to specify an inverse covariance matrix based on a restrictions matrix.
|
| Returns: | **res** β The results for the test are attributes of this results instance. |
| Return type: | ContrastResults instance |
#### Examples
```
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> A = np.identity(len(results.params))
>>> A = A[1:,:]
```
This tests that each coefficient is jointly statistically significantly different from zero.
```
>>> print(results.f_test(A))
<F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6>
```
Compare this to
```
>>> results.fvalue
330.2853392346658
>>> results.f_pvalue
4.98403096572e-10
```
```
>>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1]))
```
This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal.
```
>>> print(results.f_test(B))
<F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2>
```
Alternatively, you can specify the hypothesis tests using a string
```
>>> from statsmodels.datasets import longley
>>> from statsmodels.formula.api import ols
>>> dta = longley.load_pandas().data
>>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR'
>>> results = ols(formula, dta).fit()
>>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)'
>>> f_test = results.f_test(hypotheses)
>>> print(f_test)
<F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3>
```
See also
[`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.wald_test#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.wald_test "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.wald_test"), [`t_test`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.t_test#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.t_test "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
#### Notes
The matrix `r_matrix` is assumed to be non-singular. More precisely,
r\_matrix (pX pX.T) r\_matrix.T
is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.initialize statsmodels.tsa.statespace.structural.UnobservedComponents.initialize
=====================================================================
`UnobservedComponents.initialize()`
Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed.
statsmodels statsmodels.stats.weightstats.DescrStatsW.cov statsmodels.stats.weightstats.DescrStatsW.cov
=============================================
`DescrStatsW.cov()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.cov)
weighted covariance of data if data is 2 dimensional
assumes variables in columns and observations in rows uses default ddof
statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.HC2_se statsmodels.sandbox.regression.gmm.IVRegressionResults.HC2\_se
==============================================================
`IVRegressionResults.HC2_se()`
See statsmodels.RegressionResults
statsmodels statsmodels.regression.linear_model.OLSResults.get_robustcov_results statsmodels.regression.linear\_model.OLSResults.get\_robustcov\_results
=======================================================================
`OLSResults.get_robustcov_results(cov_type='HC1', use_t=None, **kwds)`
create new results instance with robust covariance as default
| Parameters: | * **cov\_type** (*string*) β the type of robust sandwich estimator to use. see Notes below
* **use\_t** (*bool*) β If true, then the t distribution is used for inference. If false, then the normal distribution is used. If `use_t` is None, then an appropriate default is used, which is `true` if the cov\_type is nonrobust, and `false` in all other cases.
* **kwds** (*depends on cov\_type*) β Required or optional arguments for robust covariance calculation. see Notes below
|
| Returns: | **results** β This method creates a new results instance with the requested robust covariance as the default covariance of the parameters. Inferential statistics like p-values and hypothesis tests will be based on this covariance matrix. |
| Return type: | results instance |
#### Notes
The following covariance types and required or optional arguments are currently available:
* βfixed scaleβ and optional keyword argument βscaleβ which uses
a predefined scale estimate with default equal to one.
* βHC0β, βHC1β, βHC2β, βHC3β and no keyword arguments:
heteroscedasticity robust covariance
* βHACβ and keywords
+ `maxlag` integer (required) : number of lags to use
+ `kernel callable or str (optional) : kernel` currently available kernels are [βbartlettβ, βuniformβ], default is Bartlett
+ `use_correction bool (optional) : If true, use small sample` correction
* βclusterβ and required keyword `groups`, integer group indicator
+ `groups array_like, integer (required) :` index of clusters or groups
+ `use_correction bool (optional) :` If True the sandwich covariance is calculated with a small sample correction. If False the sandwich covariance is calculated without small sample correction.
+ `df_correction bool (optional)` If True (default), then the degrees of freedom for the inferential statistics and hypothesis tests, such as pvalues, f\_pvalue, conf\_int, and t\_test and f\_test, are based on the number of groups minus one instead of the total number of observations minus the number of explanatory variables. `df_resid` of the results instance is adjusted. If False, then `df_resid` of the results instance is not adjusted.
* βhac-groupsumβ Driscoll and Kraay, heteroscedasticity and
autocorrelation robust standard errors in panel data keywords
+ `time` array\_like (required) : index of time periods
+ `maxlag` integer (required) : number of lags to use
+ `kernel callable or str (optional) : kernel` currently available kernels are [βbartlettβ, βuniformβ], default is Bartlett
+ `use_correction False or string in [βhacβ, βclusterβ] (optional) :` If False the the sandwich covariance is calulated without small sample correction. If `use_correction = βclusterβ` (default), then the same small sample correction as in the case of βcovtype=βclusterββ is used.
+ `df_correction bool (optional)` adjustment to df\_resid, see cov\_type βclusterβ above # TODO: we need more options here
* βhac-panelβ heteroscedasticity and autocorrelation robust standard
errors in panel data. The data needs to be sorted in this case, the time series for each panel unit or cluster need to be stacked. The membership to a timeseries of an individual or group can be either specified by group indicators or by increasing time periods.
keywords
+ either `groups` or `time` : array\_like (required) `groups` : indicator for groups `time` : index of time periods
+ `maxlag` integer (required) : number of lags to use
+ `kernel callable or str (optional) : kernel` currently available kernels are [βbartlettβ, βuniformβ], default is Bartlett
+ `use_correction False or string in [βhacβ, βclusterβ] (optional) :` If False the sandwich covariance is calculated without small sample correction.
+ `df_correction bool (optional)` adjustment to df\_resid, see cov\_type βclusterβ above # TODO: we need more options here
Reminder: `use_correction` in βhac-groupsumβ and βhac-panelβ is not bool, needs to be in [False, βhacβ, βclusterβ]
TODO: Currently there is no check for extra or misspelled keywords, except in the case of cov\_type `HCx`
statsmodels statsmodels.regression.linear_model.OLSResults.summary statsmodels.regression.linear\_model.OLSResults.summary
=======================================================
`OLSResults.summary(yname=None, xname=None, title=None, alpha=0.05)`
Summarize the Regression Results
| Parameters: | * **yname** (*string**,* *optional*) β Default is `y`
* **xname** (*list of strings**,* *optional*) β Default is `var_##` for ## in p the number of regressors
* **title** (*string**,* *optional*) β Title for the top table. If not None, then this replaces the default title
* **alpha** (*float*) β significance level for the confidence intervals
|
| Returns: | **smry** β this holds the summary tables and text, which can be printed or converted to various output formats. |
| Return type: | Summary instance |
See also
[`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary")
class to hold summary results
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.set_null_options statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.set\_null\_options
===============================================================================
`ZeroInflatedPoissonResults.set_null_options(llnull=None, attach_results=True, **kwds)`
set fit options for Null (constant-only) model
This resets the cache for related attributes which is potentially fragile. This only sets the option, the null model is estimated when llnull is accessed, if llnull is not yet in cache.
| Parameters: | * **llnull** (*None* *or* *float*) β If llnull is not None, then the value will be directly assigned to the cached attribute βllnullβ.
* **attach\_results** (*bool*) β Sets an internal flag whether the results instance of the null model should be attached. By default without calling this method, thenull model results are not attached and only the loglikelihood value llnull is stored.
* **kwds** (*keyword arguments*) β `kwds` are directly used as fit keyword arguments for the null model, overriding any provided defaults.
|
| Returns: | |
| Return type: | no returns, modifies attributes of this instance |
statsmodels statsmodels.sandbox.regression.gmm.GMMResults.tvalues statsmodels.sandbox.regression.gmm.GMMResults.tvalues
=====================================================
`GMMResults.tvalues()`
Return the t-statistic for a given parameter estimate.
statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.score statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.score
=====================================================================
`ZeroInflatedNegativeBinomialP.score(params)`
Score vector of model.
The gradient of logL with respect to each parameter.
| programming_docs |
statsmodels statsmodels.nonparametric.kernel_density.EstimatorSettings statsmodels.nonparametric.kernel\_density.EstimatorSettings
===========================================================
`class statsmodels.nonparametric.kernel_density.EstimatorSettings(efficient=False, randomize=False, n_res=25, n_sub=50, return_median=True, return_only_bw=False, n_jobs=-1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/_kernel_base.html#EstimatorSettings)
Object to specify settings for density estimation or regression.
`EstimatorSettings` has several proporties related to how bandwidth estimation for the `KDEMultivariate`, `KDEMultivariateConditional`, `KernelReg` and `CensoredKernelReg` classes behaves.
| Parameters: | * **efficient** (*bool**,* *optional*) β If True, the bandwidth estimation is to be performed efficiently β by taking smaller sub-samples and estimating the scaling factor of each subsample. This is useful for large samples (nobs >> 300) and/or multiple variables (k\_vars > 3). If False (default), all data is used at the same time.
* **randomize** (*bool**,* *optional*) β If True, the bandwidth estimation is to be performed by taking `n_res` random resamples (with replacement) of size `n_sub` from the full sample. If set to False (default), the estimation is performed by slicing the full sample in sub-samples of size `n_sub` so that all samples are used once.
* **n\_sub** (*int**,* *optional*) β Size of the sub-samples. Default is 50.
* **n\_res** (*int**,* *optional*) β The number of random re-samples used to estimate the bandwidth. Only has an effect if `randomize == True`. Default value is 25.
* **return\_median** (*bool**,* *optional*) β If True (default), the estimator uses the median of all scaling factors for each sub-sample to estimate the bandwidth of the full sample. If False, the estimator uses the mean.
* **return\_only\_bw** (*bool**,* *optional*) β If True, the estimator is to use the bandwidth and not the scaling factor. This is *not* theoretically justified. Should be used only for experimenting.
* **n\_jobs** (*int**,* *optional*) β The number of jobs to use for parallel estimation with `joblib.Parallel`. Default is -1, meaning `n_cores - 1`, with `n_cores` the number of available CPU cores. See the [joblib documentation](https://pythonhosted.org/joblib/parallel.html) for more details.
|
#### Examples
```
>>> settings = EstimatorSettings(randomize=True, n_jobs=3)
>>> k_dens = KDEMultivariate(data, var_type, defaults=settings)
```
#### Methods
statsmodels statsmodels.regression.linear_model.RegressionResults.normalized_cov_params statsmodels.regression.linear\_model.RegressionResults.normalized\_cov\_params
==============================================================================
`RegressionResults.normalized_cov_params()`
statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.summary statsmodels.regression.mixed\_linear\_model.MixedLMResults.summary
==================================================================
`MixedLMResults.summary(yname=None, xname_fe=None, xname_re=None, title=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.summary)
Summarize the mixed model regression results.
| Parameters: | * **yname** (*string**,* *optional*) β Default is `y`
* **xname\_fe** (*list of strings**,* *optional*) β Fixed effects covariate names
* **xname\_re** (*list of strings**,* *optional*) β Random effects covariate names
* **title** (*string**,* *optional*) β Title for the top table. If not None, then this replaces the default title
* **alpha** (*float*) β significance level for the confidence intervals
|
| Returns: | **smry** β this holds the summary tables and text, which can be printed or converted to various output formats. |
| Return type: | Summary instance |
See also
[`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary")
class to hold summary results
statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.cov_params_func_l1 statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.cov\_params\_func\_l1
=====================================================================================
`ZeroInflatedNegativeBinomialP.cov_params_func_l1(likelihood_model, xopt, retvals)`
Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit.
Returns a full cov\_params matrix, with entries corresponding to zeroβd values set to np.nan.
statsmodels statsmodels.tsa.vector_ar.vecm.VECM.predict statsmodels.tsa.vector\_ar.vecm.VECM.predict
============================================
`VECM.predict(params, exog=None, *args, **kwargs)`
After a model has been fit predict returns the fitted values.
This is a placeholder intended to be overwritten by individual models.
statsmodels statsmodels.regression.recursive_ls.RecursiveLS.predict statsmodels.regression.recursive\_ls.RecursiveLS.predict
========================================================
`RecursiveLS.predict(params, exog=None, *args, **kwargs)`
After a model has been fit predict returns the fitted values.
This is a placeholder intended to be overwritten by individual models.
statsmodels statsmodels.tsa.stattools.ccovf statsmodels.tsa.stattools.ccovf
===============================
`statsmodels.tsa.stattools.ccovf(x, y, unbiased=True, demean=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#ccovf)
crosscovariance for 1D
| Parameters: | * **y** (*x**,*) β time series data
* **unbiased** (*boolean*) β if True, then denominators is n-k, otherwise n
|
| Returns: | **ccovf** β autocovariance function |
| Return type: | array |
#### Notes
This uses np.correlate which does full convolution. For very long time series it is recommended to use fft convolution instead.
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llr statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.llr
================================================================
`ZeroInflatedPoissonResults.llr()`
statsmodels statsmodels.discrete.discrete_model.ProbitResults.resid_response statsmodels.discrete.discrete\_model.ProbitResults.resid\_response
==================================================================
`ProbitResults.resid_response()`
The response residuals
#### Notes
Response residuals are defined to be
\[y - p\] where \(p=cdf(X\beta)\).
statsmodels statsmodels.regression.linear_model.OLSResults.aic statsmodels.regression.linear\_model.OLSResults.aic
===================================================
`OLSResults.aic()`
statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.score_cu statsmodels.sandbox.regression.gmm.LinearIVGMM.score\_cu
========================================================
`LinearIVGMM.score_cu(params, epsilon=None, centered=True)`
statsmodels statsmodels.tools.numdiff.approx_hess3 statsmodels.tools.numdiff.approx\_hess3
=======================================
`statsmodels.tools.numdiff.approx_hess3(x, f, epsilon=None, args=(), kwargs={})` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/numdiff.html#approx_hess3)
Calculate Hessian with finite difference derivative approximation
| Parameters: | * **x** (*array\_like*) β value at which function derivative is evaluated
* **f** (*function*) β function of one array f(x, `*args`, `**kwargs`)
* **epsilon** (*float* *or* *array-like**,* *optional*) β Stepsize used, if None, then stepsize is automatically chosen according to EPS\*\*(1/4)\*x.
* **args** (*tuple*) β Arguments for function `f`.
* **kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) β Keyword arguments for function `f`.
|
| Returns: | **hess** β array of partial second derivatives, Hessian |
| Return type: | ndarray |
#### Notes
Equation (9) in Ridout. Computes the Hessian as:
```
1/(4*d_j*d_k) * ((f(x + d[j]*e[j] + d[k]*e[k]) - f(x + d[j]*e[j]
- d[k]*e[k])) -
(f(x - d[j]*e[j] + d[k]*e[k]) - f(x - d[j]*e[j]
- d[k]*e[k]))
```
where e[j] is a vector with element j == 1 and the rest are zero and d[i] is epsilon[i].
#### References
Ridout, M.S. (2009) Statistical applications of the complex-step method of numerical differentiation. The American Statistician, 63, 66-74 This is an alias for approx\_hess3
statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.nloglikeobs statsmodels.miscmodels.count.PoissonZiGMLE.nloglikeobs
======================================================
`PoissonZiGMLE.nloglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/count.html#PoissonZiGMLE.nloglikeobs)
Loglikelihood of Poisson model
| Parameters: | **params** (*array-like*) β The parameters of the model. |
| Returns: | |
| Return type: | The log likelihood of the model evaluated at `params` |
#### Notes
\[\ln L=\sum\_{i=1}^{n}\left[-\lambda\_{i}+y\_{i}x\_{i}^{\prime}\beta-\ln y\_{i}!\right]\]
statsmodels statsmodels.discrete.discrete_model.Poisson.cdf statsmodels.discrete.discrete\_model.Poisson.cdf
================================================
`Poisson.cdf(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.cdf)
Poisson model cumulative distribution function
| Parameters: | **X** (*array-like*) β `X` is the linear predictor of the model. See notes. |
| Returns: | |
| Return type: | The value of the Poisson CDF at each point. |
#### Notes
The CDF is defined as
\[\exp\left(-\lambda\right)\sum\_{i=0}^{y}\frac{\lambda^{i}}{i!}\] where \(\lambda\) assumes the loglinear model. I.e.,
\[\ln\lambda\_{i}=X\beta\] The parameter `X` is \(X\beta\) in the above formula.
statsmodels statsmodels.genmod.cov_struct.Autoregressive statsmodels.genmod.cov\_struct.Autoregressive
=============================================
`class statsmodels.genmod.cov_struct.Autoregressive(dist_func=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Autoregressive)
A first-order autoregressive working dependence structure.
The dependence is defined in terms of the `time` component of the parent GEE class, which defaults to the index position of each value within its cluster, based on the order of values in the input data set. Time represents a potentially multidimensional index from which distances between pairs of observations can be determined.
The correlation between two observations in the same cluster is dep\_params^distance, where `dep_params` contains the (scalar) autocorrelation parameter to be estimated, and `distance` is the distance between the two observations, calculated from their corresponding time values. `time` is stored as an n\_obs x k matrix, where `k` represents the number of dimensions in the time index.
The autocorrelation parameter is estimated using weighted nonlinear least squares, regressing each value within a cluster on each preceeding value in the same cluster.
| Parameters: | **dist\_func** (*function from R^k x R^k to R^+**,* *optional*) β A function that computes the distance between the two observations based on their `time` values. |
#### References
B Rosner, A Munoz. Autoregressive modeling for the analysis of longitudinal data with unequally spaced examinations. Statistics in medicine. Vol 7, 59-71, 1988.
#### Methods
| | |
| --- | --- |
| [`covariance_matrix`](statsmodels.genmod.cov_struct.autoregressive.covariance_matrix#statsmodels.genmod.cov_struct.Autoregressive.covariance_matrix "statsmodels.genmod.cov_struct.Autoregressive.covariance_matrix")(endog\_expval, index) | Returns the working covariance or correlation matrix for a given cluster of data. |
| [`covariance_matrix_solve`](statsmodels.genmod.cov_struct.autoregressive.covariance_matrix_solve#statsmodels.genmod.cov_struct.Autoregressive.covariance_matrix_solve "statsmodels.genmod.cov_struct.Autoregressive.covariance_matrix_solve")(expval, index, β¦) | Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. |
| [`initialize`](statsmodels.genmod.cov_struct.autoregressive.initialize#statsmodels.genmod.cov_struct.Autoregressive.initialize "statsmodels.genmod.cov_struct.Autoregressive.initialize")(model) | Called by GEE, used by implementations that need additional setup prior to running `fit`. |
| [`summary`](statsmodels.genmod.cov_struct.autoregressive.summary#statsmodels.genmod.cov_struct.Autoregressive.summary "statsmodels.genmod.cov_struct.Autoregressive.summary")() | Returns a text summary of the current estimate of the dependence structure. |
| [`update`](statsmodels.genmod.cov_struct.autoregressive.update#statsmodels.genmod.cov_struct.Autoregressive.update "statsmodels.genmod.cov_struct.Autoregressive.update")(params) | Updates the association parameter values based on the current regression coefficients. |
statsmodels statsmodels.tsa.arima_process.ArmaProcess.impulse_response statsmodels.tsa.arima\_process.ArmaProcess.impulse\_response
============================================================
`ArmaProcess.impulse_response(leads=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess.impulse_response)
Get the impulse response function (MA representation) for ARMA process
| Parameters: | * **ma** (*array\_like**,* *1d*) β moving average lag polynomial
* **ar** (*array\_like**,* *1d*) β auto regressive lag polynomial
* **leads** (*int*) β number of observations to calculate
|
| Returns: | **ir** β impulse response function with nobs elements |
| Return type: | array, 1d |
#### Notes
This is the same as finding the MA representation of an ARMA(p,q). By reversing the role of ar and ma in the function arguments, the returned result is the AR representation of an ARMA(p,q), i.e
ma\_representation = arma\_impulse\_response(ar, ma, leads=100) ar\_representation = arma\_impulse\_response(ma, ar, leads=100)
Fully tested against matlab
#### Examples
AR(1)
```
>>> arma_impulse_response([1.0, -0.8], [1.], leads=10)
array([ 1. , 0.8 , 0.64 , 0.512 , 0.4096 ,
0.32768 , 0.262144 , 0.2097152 , 0.16777216, 0.13421773])
```
this is the same as
```
>>> 0.8**np.arange(10)
array([ 1. , 0.8 , 0.64 , 0.512 , 0.4096 ,
0.32768 , 0.262144 , 0.2097152 , 0.16777216, 0.13421773])
```
MA(2)
```
>>> arma_impulse_response([1.0], [1., 0.5, 0.2], leads=10)
array([ 1. , 0.5, 0.2, 0. , 0. , 0. , 0. , 0. , 0. , 0. ])
```
ARMA(1,2)
```
>>> arma_impulse_response([1.0, -0.8], [1., 0.5, 0.2], leads=10)
array([ 1. , 1.3 , 1.24 , 0.992 , 0.7936 ,
0.63488 , 0.507904 , 0.4063232 , 0.32505856, 0.26004685])
```
statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.jtest statsmodels.sandbox.regression.gmm.IVGMMResults.jtest
=====================================================
`IVGMMResults.jtest()`
overidentification test
I guess this is missing a division by nobs, whatβs the normalization in jval ?
statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fitgmm_cu statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fitgmm\_cu
============================================================
`NonlinearIVGMM.fitgmm_cu(start, optim_method='bfgs', optim_args=None)`
estimate parameters using continuously updating GMM
| Parameters: | **start** (*array\_like*) β starting values for minimization |
| Returns: | **paramest** β estimated parameters |
| Return type: | array |
#### Notes
todo: add fixed parameter option, not here ???
uses scipy.optimize.fmin
statsmodels statsmodels.graphics.agreement.mean_diff_plot statsmodels.graphics.agreement.mean\_diff\_plot
===============================================
`statsmodels.graphics.agreement.mean_diff_plot(m1, m2, sd_limit=1.96, ax=None, scatter_kwds=None, mean_line_kwds=None, limit_lines_kwds=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/agreement.html#mean_diff_plot)
Tukeyβs Mean Difference Plot.
Tukeyβs Mean Difference Plot (also known as a Bland-Altman plot) is a graphical method to analyze the differences between two methods of measurement. The mean of the measures is plotted against their difference.
For more information see <https://en.wikipedia.org/wiki/Bland-Altman_plot>
| Parameters: | * **m2** (*m1**,*) β
* **sd\_limit** (*float**,* *default 1.96*) β The limit of agreements expressed in terms of the standard deviation of the differences. If `md` is the mean of the differences, and `sd` is the standard deviation of those differences, then the limits of agreement that will be plotted will be md - sd\_limit \* sd, md + sd\_limit \* sd The default of 1.96 will produce 95% confidence intervals for the means of the differences. If sd\_limit = 0, no limits will be plotted, and the ylimit of the plot defaults to 3 standard deviatons on either side of the mean.
* **ax** (*matplotlib AxesSubplot instance**,* *optional*) β If `ax` is None, then a figure is created. If an axis instance is given, the mean difference plot is drawn on the axis.
* **scatter\_kwargs** (*keywords*) β Options to to style the scatter plot. Accepts any keywords for the matplotlib Axes.scatter plotting method
* **mean\_line\_kwds** (*keywords*) β Options to to style the scatter plot. Accepts any keywords for the matplotlib Axes.axhline plotting method
* **limit\_lines\_kwds** (*keywords*) β Options to to style the scatter plot. Accepts any keywords for the matplotlib Axes.axhline plotting method
|
| Returns: | **fig** β If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. |
| Return type: | matplotlib Figure |
#### References
Bland JM, Altman DG (1986). βStatistical methods for assessing agreement between two methods of clinical measurementβ
#### Example
Load relevant libraries.
```
>>> import statsmodels.api as sm
>>> import numpy as np
>>> import matplotlib.pyplot as plt
```
Making a mean difference plot.
```
>>> # Seed the random number generator.
>>> # This ensures that the results below are reproducible.
>>> np.random.seed(9999)
>>> m1 = np.random.random(20)
>>> m2 = np.random.random(20)
>>> f, ax = plt.subplots(1, figsize = (8,5))
>>> sm.graphics.mean_diff_plot(m1, m2, ax = ax)
>>> plt.show()
```
([Source code](../plots/graphics-mean_diff_plot.py), [png](../plots/graphics-mean_diff_plot.png), [hires.png](../plots/graphics-mean_diff_plot.hires.png), [pdf](../plots/graphics-mean_diff_plot.pdf))
statsmodels statsmodels.discrete.discrete_model.MNLogit.loglike statsmodels.discrete.discrete\_model.MNLogit.loglike
====================================================
`MNLogit.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MNLogit.loglike)
Log-likelihood of the multinomial logit model.
| Parameters: | **params** (*array-like*) β The parameters of the multinomial logit model. |
| Returns: | **loglike** β The log-likelihood function of the model evaluated at `params`. See notes. |
| Return type: | float |
#### Notes
\[\ln L=\sum\_{i=1}^{n}\sum\_{j=0}^{J}d\_{ij}\ln\left(\frac{\exp\left(\beta\_{j}^{\prime}x\_{i}\right)}{\sum\_{k=0}^{J}\exp\left(\beta\_{k}^{\prime}x\_{i}\right)}\right)\] where \(d\_{ij}=1\) if individual `i` chose alternative `j` and 0 if not.
| programming_docs |
statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.moment statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.moment
===================================================================
`ExpTransf_gen.moment(n, *args, **kwds)`
n-th order non-central moment of distribution.
| Parameters: | * **n** (*int**,* *n >= 1*) β Order of moment.
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information).
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.acf statsmodels.sandbox.tsa.fftarma.ArmaFft.acf
===========================================
`ArmaFft.acf(lags=None)`
Theoretical autocorrelation function of an ARMA process
| Parameters: | * **ar** (*array\_like**,* *1d*) β coefficient for autoregressive lag polynomial, including zero lag
* **ma** (*array\_like**,* *1d*) β coefficient for moving-average lag polynomial, including zero lag
* **lags** (*int*) β number of terms (lags plus zero lag) to include in returned acf
|
| Returns: | **acf** β autocorrelation of ARMA process given by ar, ma |
| Return type: | array |
See also
`arma_acovf`, [`acf`](#statsmodels.sandbox.tsa.fftarma.ArmaFft.acf "statsmodels.sandbox.tsa.fftarma.ArmaFft.acf"), [`acovf`](statsmodels.sandbox.tsa.fftarma.armafft.acovf#statsmodels.sandbox.tsa.fftarma.ArmaFft.acovf "statsmodels.sandbox.tsa.fftarma.ArmaFft.acovf")
statsmodels statsmodels.regression.linear_model.RegressionResults.rsquared_adj statsmodels.regression.linear\_model.RegressionResults.rsquared\_adj
====================================================================
`RegressionResults.rsquared_adj()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.rsquared_adj)
statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.predict statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.predict
=============================================================================
`MarkovRegression.predict(params, start=None, end=None, probabilities=None, conditional=False)`
In-sample prediction and out-of-sample forecasting
| Parameters: | * **params** (*array*) β Parameters at which to form predictions
* **start** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation.
* **end** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample.
* **probabilities** (*string* *or* *array\_like**,* *optional*) β Specifies the weighting probabilities used in constructing the prediction as a weighted average. If a string, can be βpredictedβ, βfilteredβ, or βsmoothedβ. Otherwise can be an array of probabilities to use. Default is smoothed.
* **conditional** (*boolean* *or* *int**,* *optional*) β Whether or not to return predictions conditional on current or past regimes. If False, returns a single vector of weighted predictions. If True or 1, returns predictions conditional on the current regime. For larger integers, returns predictions conditional on the current regime and some number of past regimes.
|
| Returns: | **predict** β Array of out of in-sample predictions and / or out-of-sample forecasts. |
| Return type: | array |
statsmodels statsmodels.duration.hazard_regression.PHRegResults.wald_test_terms statsmodels.duration.hazard\_regression.PHRegResults.wald\_test\_terms
======================================================================
`PHRegResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)`
Compute a sequence of Wald tests for terms over multiple columns
This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero.
`Terms` are defined by the underlying formula or by string matching.
| Parameters: | * **skip\_single** (*boolean*) β If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included.
* **extra\_constraints** (*ndarray*) β not tested yet
* **combine\_terms** (*None* *or* *list of strings*) β Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test.
|
| Returns: | **test\_result** β The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. |
| Return type: | result instance |
#### Examples
```
>>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit()
>>> res_ols.wald_test_terms()
<class 'statsmodels.stats.contrast.WaldTestResults'>
F P>F df constraint df denom
Intercept 279.754525 2.37985521351e-22 1 51
C(Duration, Sum) 5.367071 0.0245738436636 1 51
C(Weight, Sum) 12.432445 3.99943118767e-05 2 51
C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51
```
```
>>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0')
>>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight'])
>>> print(wt)
chi2 P>chi2 df constraint
Intercept 15.695625 7.43960374424e-05 1
C(Weight) 16.132616 0.000313940174705 2
C(Duration) 1.009147 0.315107378931 1
C(Weight):C(Duration) 0.216694 0.897315972824 2
Duration 11.187849 0.010752286833 3
Weight 30.263368 4.32586407145e-06 4
```
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_pearson statsmodels.genmod.generalized\_estimating\_equations.GEEResults.resid\_pearson
===============================================================================
`GEEResults.resid_pearson()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid_pearson)
statsmodels statsmodels.regression.linear_model.RegressionResults.summary statsmodels.regression.linear\_model.RegressionResults.summary
==============================================================
`RegressionResults.summary(yname=None, xname=None, title=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.summary)
Summarize the Regression Results
| Parameters: | * **yname** (*string**,* *optional*) β Default is `y`
* **xname** (*list of strings**,* *optional*) β Default is `var_##` for ## in p the number of regressors
* **title** (*string**,* *optional*) β Title for the top table. If not None, then this replaces the default title
* **alpha** (*float*) β significance level for the confidence intervals
|
| Returns: | **smry** β this holds the summary tables and text, which can be printed or converted to various output formats. |
| Return type: | Summary instance |
See also
[`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary")
class to hold summary results
statsmodels statsmodels.stats.diagnostic.CompareJ.run statsmodels.stats.diagnostic.CompareJ.run
=========================================
`CompareJ.run(results_x, results_z, attach=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#CompareJ.run)
run J-test for non-nested models
| Parameters: | * **results\_x** (*Result instance*) β result instance of first model
* **results\_z** (*Result instance*) β result instance of second model
* **attach** (*bool*) β If true, then the intermediate results are attached to the instance.
|
| Returns: | * **tstat** (*float*) β t statistic for the test that including the fitted values of the first model in the second model has no effect.
* **pvalue** (*float*) β two-sided pvalue for the t statistic
|
#### Notes
Tests of non-nested hypothesis might not provide unambiguous answers. The test should be performed in both directions and it is possible that both or neither test rejects. see ??? for more information.
#### References
???
statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.initialize_stationary statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.initialize\_stationary
=================================================================================
`KalmanSmoother.initialize_stationary()`
Initialize the statespace model as stationary.
statsmodels statsmodels.discrete.discrete_model.Logit.score statsmodels.discrete.discrete\_model.Logit.score
================================================
`Logit.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Logit.score)
Logit model score (gradient) vector of the log-likelihood
| Parameters: | **params** (*array-like*) β The parameters of the model |
| Returns: | **score** β The score vector of the model, i.e. the first derivative of the loglikelihood function, evaluated at `params` |
| Return type: | ndarray, 1-D |
#### Notes
\[\frac{\partial\ln L}{\partial\beta}=\sum\_{i=1}^{n}\left(y\_{i}-\Lambda\_{i}\right)x\_{i}\]
statsmodels statsmodels.stats.power.NormalIndPower.power statsmodels.stats.power.NormalIndPower.power
============================================
`NormalIndPower.power(effect_size, nobs1, alpha, ratio=1, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#NormalIndPower.power)
Calculate the power of a z-test for two independent sample
| Parameters: | * **effect\_size** (*float*) β standardized effect size, difference between the two means divided by the standard deviation. effect size has to be positive.
* **nobs1** (*int* *or* *float*) β number of observations of sample 1. The number of observations of sample two is ratio times the size of sample 1, i.e. `nobs2 = nobs1 * ratio` `ratio` can be set to zero in order to get the power for a one sample test.
* **alpha** (*float in interval* *(**0**,**1**)*) β significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true.
* **ratio** (*float*) β ratio of the number of observations in sample 2 relative to sample 1. see description of nobs1
* **alternative** (*string**,* *'two-sided'* *(**default**)**,* *'larger'**,* *'smaller'*) β extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. The one-sided test can be either βlargerβ, βsmallerβ.
|
| Returns: | **power** β Power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. |
| Return type: | float |
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults statsmodels.discrete.count\_model.ZeroInflatedPoissonResults
============================================================
`class statsmodels.discrete.count_model.ZeroInflatedPoissonResults(model, mlefit, cov_type='nonrobust', cov_kwds=None, use_t=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#ZeroInflatedPoissonResults)
A results class for Zero Inflated Poisson
| Parameters: | * **model** (*A DiscreteModel instance*) β
* **params** (*array-like*) β The parameters of a fitted model.
* **hessian** (*array-like*) β The hessian of the fitted model.
* **scale** (*float*) β A scale parameter for the covariance matrix.
|
| Returns: | * *\*Attributes\**
* **aic** (*float*) β Akaike information criterion. `-2*(llf - p)` where `p` is the number of regressors including the intercept.
* **bic** (*float*) β Bayesian information criterion. `-2*llf + ln(nobs)*p` where `p` is the number of regressors including the intercept.
* **bse** (*array*) β The standard errors of the coefficients.
* **df\_resid** (*float*) β See model definition.
* **df\_model** (*float*) β See model definition.
* **fitted\_values** (*array*) β Linear predictor XB.
* **llf** (*float*) β Value of the loglikelihood
* **llnull** (*float*) β Value of the constant-only loglikelihood
* **llr** (*float*) β Likelihood ratio chi-squared statistic; `-2*(llnull - llf)`
* **llr\_pvalue** (*float*) β The chi-squared probability of getting a log-likelihood ratio statistic greater than llr. llr has a chi-squared distribution with degrees of freedom `df_model`.
* **prsquared** (*float*) β McFaddenβs pseudo-R-squared. `1 - (llf / llnull)`
|
#### Methods
| | |
| --- | --- |
| [`aic`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.aic#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.aic "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.aic")() | |
| [`bic`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.bic#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.bic "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.bic")() | |
| [`bse`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.bse#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.bse "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.bse")() | |
| [`conf_int`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.conf_int#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.conf_int "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. |
| [`cov_params`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.cov_params#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.cov_params "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.cov_params")([r\_matrix, column, scale, cov\_p, β¦]) | Returns the variance/covariance matrix. |
| [`f_test`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.f_test#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.f_test "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. |
| [`fittedvalues`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.fittedvalues#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.fittedvalues "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.fittedvalues")() | |
| [`get_margeff`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.get_margeff#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.get_margeff "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.get_margeff")([at, method, atexog, dummy, count]) | Get marginal effects of the fitted model. |
| [`initialize`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.initialize#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.initialize "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.initialize")(model, params, \*\*kwd) | |
| [`llf`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.llf#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llf "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llf")() | |
| [`llnull`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.llnull#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llnull "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llnull")() | |
| [`llr`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.llr#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llr "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llr")() | |
| [`llr_pvalue`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.llr_pvalue#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llr_pvalue "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llr_pvalue")() | |
| [`load`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.load#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.load "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.load")(fname) | load a pickle, (class method) |
| [`normalized_cov_params`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.normalized_cov_params#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.normalized_cov_params "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.normalized_cov_params")() | |
| [`predict`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.predict#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.predict "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. |
| [`prsquared`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.prsquared#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.prsquared "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.prsquared")() | |
| [`pvalues`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.pvalues#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.pvalues "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.pvalues")() | |
| [`remove_data`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.remove_data#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.remove_data "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.remove_data")() | remove data arrays, all nobs arrays from result and model |
| [`resid`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.resid#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.resid "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.resid")() | Residuals |
| [`save`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.save#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.save "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.save")(fname[, remove\_data]) | save a pickle of this instance |
| [`set_null_options`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.set_null_options#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.set_null_options "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.set_null_options")([llnull, attach\_results]) | set fit options for Null (constant-only) model |
| [`summary`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.summary#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.summary "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.summary")([yname, xname, title, alpha, yname\_list]) | Summarize the Regression Results |
| [`summary2`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.summary2#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.summary2 "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.summary2")([yname, xname, title, alpha, β¦]) | Experimental function to summarize regression results |
| [`t_test`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.t_test#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.t_test "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q |
| [`t_test_pairwise`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.t_test_pairwise#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.t_test_pairwise "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.t_test_pairwise")(term\_name[, method, alpha, β¦]) | perform pairwise t\_test with multiple testing corrected p-values |
| [`tvalues`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.tvalues#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.tvalues "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.tvalues")() | Return the t-statistic for a given parameter estimate. |
| [`wald_test`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.wald_test#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.wald_test "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, β¦]) | Compute a Wald-test for a joint linear hypothesis. |
| [`wald_test_terms`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.wald_test_terms#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.wald_test_terms "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.wald_test_terms")([skip\_single, β¦]) | Compute a sequence of Wald tests for terms over multiple columns |
#### Attributes
| | |
| --- | --- |
| `use_t` | |
| programming_docs |
statsmodels statsmodels.tsa.arima_model.ARIMA.initialize statsmodels.tsa.arima\_model.ARIMA.initialize
=============================================
`ARIMA.initialize()`
Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed.
statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.loglike statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.loglike
==================================================================
`KalmanSmoother.loglike(**kwargs)`
Calculate the loglikelihood associated with the statespace model.
| Parameters: | **\*\*kwargs** β Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. |
| Returns: | **loglike** β The joint loglikelihood. |
| Return type: | float |
statsmodels statsmodels.regression.linear_model.OLSResults.conf_int statsmodels.regression.linear\_model.OLSResults.conf\_int
=========================================================
`OLSResults.conf_int(alpha=0.05, cols=None)`
Returns the confidence interval of the fitted parameters.
| Parameters: | * **alpha** (*float**,* *optional*) β The `alpha` level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval.
* **cols** (*array-like**,* *optional*) β `cols` specifies which confidence intervals to return
|
#### Notes
The confidence interval is based on Studentβs t-distribution.
statsmodels statsmodels.tsa.holtwinters.Holt.hessian statsmodels.tsa.holtwinters.Holt.hessian
========================================
`Holt.hessian(params)`
The Hessian matrix of the model
statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.entropy statsmodels.sandbox.distributions.transformed.Transf\_gen.entropy
=================================================================
`Transf_gen.entropy(*args, **kwds)`
Differential entropy of the RV.
| Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information).
* **loc** (*array\_like**,* *optional*) β Location parameter (default=0).
* **scale** (*array\_like**,* *optional* *(**continuous distributions only**)*) β Scale parameter (default=1).
|
#### Notes
Entropy is defined base `e`:
```
>>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
>>> np.allclose(drv.entropy(), np.log(2.0))
True
```
statsmodels statsmodels.stats.outliers_influence.OLSInfluence.resid_studentized_internal statsmodels.stats.outliers\_influence.OLSInfluence.resid\_studentized\_internal
===============================================================================
`OLSInfluence.resid_studentized_internal()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.resid_studentized_internal)
(cached attribute) studentized residuals using variance from OLS
this uses sigma from original estimate does not require leave one out loop
statsmodels statsmodels.regression.linear_model.RegressionResults.HC0_se statsmodels.regression.linear\_model.RegressionResults.HC0\_se
==============================================================
`RegressionResults.HC0_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.HC0_se)
See statsmodels.RegressionResults
statsmodels statsmodels.genmod.families.family.NegativeBinomial.fitted statsmodels.genmod.families.family.NegativeBinomial.fitted
==========================================================
`NegativeBinomial.fitted(lin_pred)`
Fitted values based on linear predictors lin\_pred.
| Parameters: | **lin\_pred** (*array*) β Values of the linear predictor of the model. \(X \cdot \beta\) in a classical linear model. |
| Returns: | **mu** β The mean response variables given by the inverse of the link function. |
| Return type: | array |
statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.normalized_cov_params statsmodels.discrete.discrete\_model.NegativeBinomialResults.normalized\_cov\_params
====================================================================================
`NegativeBinomialResults.normalized_cov_params()`
statsmodels statsmodels.robust.norms.LeastSquares.weights statsmodels.robust.norms.LeastSquares.weights
=============================================
`LeastSquares.weights(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#LeastSquares.weights)
The least squares estimator weighting function for the IRLS algorithm.
The psi function scaled by the input z
| Parameters: | **z** (*array-like*) β 1d array |
| Returns: | **weights** β weights(z) = np.ones(z.shape) |
| Return type: | array |
statsmodels statsmodels.sandbox.regression.gmm.GMMResults.t_test statsmodels.sandbox.regression.gmm.GMMResults.t\_test
=====================================================
`GMMResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)`
Compute a t-test for a each linear hypothesis of the form Rb = q
| Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) β
+ array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β An optional `scale` to use. Default is the scale specified by the model fit.
* **use\_t** (*bool**,* *optional*) β If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution.
|
| Returns: | **res** β The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. |
| Return type: | ContrastResults instance |
#### Examples
```
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> r = np.zeros_like(results.params)
>>> r[5:] = [1,-1]
>>> print(r)
[ 0. 0. 0. 0. 0. 1. -1.]
```
r tests that the coefficients on the 5th and 6th independent variable are the same.
```
>>> T_test = results.t_test(r)
>>> print(T_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037
==============================================================================
>>> T_test.effect
-1829.2025687192481
>>> T_test.sd
455.39079425193762
>>> T_test.tvalue
-4.0167754636411717
>>> T_test.pvalue
0.0015163772380899498
```
Alternatively, you can specify the hypothesis tests using a string
```
>>> from statsmodels.formula.api import ols
>>> dta = sm.datasets.longley.load_pandas().data
>>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR'
>>> results = ols(formula, dta).fit()
>>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1'
>>> t_test = results.t_test(hypotheses)
>>> print(t_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 15.0977 84.937 0.178 0.863 -177.042 207.238
c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915
c2 1.0001 0.249 0.000 1.000 0.437 1.563
==============================================================================
```
See also
[`tvalues`](statsmodels.sandbox.regression.gmm.gmmresults.tvalues#statsmodels.sandbox.regression.gmm.GMMResults.tvalues "statsmodels.sandbox.regression.gmm.GMMResults.tvalues")
individual t statistics
[`f_test`](statsmodels.sandbox.regression.gmm.gmmresults.f_test#statsmodels.sandbox.regression.gmm.GMMResults.f_test "statsmodels.sandbox.regression.gmm.GMMResults.f_test")
for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.regime_transition_matrix statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.regime\_transition\_matrix
========================================================================================================
`MarkovAutoregression.regime_transition_matrix(params, exog_tvtp=None)`
Construct the left-stochastic transition matrix
#### Notes
This matrix will either be shaped (k\_regimes, k\_regimes, 1) or if there are time-varying transition probabilities, it will be shaped (k\_regimes, k\_regimes, nobs).
The (i,j)th element of this matrix is the probability of transitioning from regime j to regime i; thus the previous regime is represented in a column and the next regime is represented by a row.
It is left-stochastic, meaning that each column sums to one (because it is certain that from one regime (j) you will transition to *some other regime*).
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_smoother_output statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.set\_smoother\_output
==============================================================================
`DynamicFactor.set_smoother_output(smoother_output=None, **kwargs)`
Set the smoother output
The smoother can produce several types of results. The smoother output variable controls which are calculated and returned.
| Parameters: | * **smoother\_output** (*integer**,* *optional*) β Bitmask value to set the smoother output to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the smoother output by setting individual boolean flags.
|
#### Notes
This method is rarely used. See the corresponding function in the `KalmanSmoother` class for details.
statsmodels statsmodels.discrete.discrete_model.Poisson.score_obs statsmodels.discrete.discrete\_model.Poisson.score\_obs
=======================================================
`Poisson.score_obs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.score_obs)
Poisson model Jacobian of the log-likelihood for each observation
| Parameters: | **params** (*array-like*) β The parameters of the model |
| Returns: | **score** β The score vector (nobs, k\_vars) of the model evaluated at `params` |
| Return type: | array-like |
#### Notes
\[\frac{\partial\ln L\_{i}}{\partial\beta}=\left(y\_{i}-\lambda\_{i}\right)x\_{i}\] for observations \(i=1,...,n\)
where the loglinear model is assumed
\[\ln\lambda\_{i}=x\_{i}\beta\]
statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.score statsmodels.discrete.discrete\_model.NegativeBinomial.score
===========================================================
`NegativeBinomial.score(params)`
Score vector of model.
The gradient of logL with respect to each parameter.
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.get_margeff statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.get\_margeff
====================================================================================
`ZeroInflatedGeneralizedPoissonResults.get_margeff(at='overall', method='dydx', atexog=None, dummy=False, count=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#ZeroInflatedGeneralizedPoissonResults.get_margeff)
Get marginal effects of the fitted model.
Not yet implemented for Zero Inflated Models
statsmodels statsmodels.regression.mixed_linear_model.MixedLM.predict statsmodels.regression.mixed\_linear\_model.MixedLM.predict
===========================================================
`MixedLM.predict(params, exog=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.predict)
Return predicted values from a design matrix.
| Parameters: | * **params** (*array-like*) β Parameters of a mixed linear model. Can be either a MixedLMParams instance, or a vector containing the packed model parameters in which the fixed effects parameters are at the beginning of the vector, or a vector containing only the fixed effects parameters.
* **exog** (*array-like**,* *optional*) β Design / exogenous data for the fixed effects. Model exog is used if None.
|
| Returns: | * *An array of fitted values. Note that these predicted values*
* *only reflect the fixed effects mean structure of the model.*
|
statsmodels statsmodels.tsa.arima_model.ARIMAResults.maparams statsmodels.tsa.arima\_model.ARIMAResults.maparams
==================================================
`ARIMAResults.maparams()`
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov\_params
=============================================================
`SARIMAXResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)`
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar.
| Parameters: | * **r\_matrix** (*array-like*) β Can be 1d, or 2d. Can be used alone or with other.
* **column** (*array-like**,* *optional*) β Must be used on its own. Can be 0d or 1d see below.
* **scale** (*float**,* *optional*) β Can be specified or not. Default is None, which means that the scale argument is taken from the model.
* **other** (*array-like**,* *optional*) β Can be used when r\_matrix is specified.
|
| Returns: | **cov** β covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. |
| Return type: | ndarray |
#### Notes
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)`
If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T`
If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T`
If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d
OR
`(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d
statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.score_obs statsmodels.miscmodels.count.PoissonZiGMLE.score\_obs
=====================================================
`PoissonZiGMLE.score_obs(params, **kwds)`
Jacobian/Gradient of log-likelihood evaluated at params for each observation.
statsmodels statsmodels.graphics.boxplots.beanplot statsmodels.graphics.boxplots.beanplot
======================================
`statsmodels.graphics.boxplots.beanplot(data, ax=None, labels=None, positions=None, side='both', jitter=False, plot_opts={})` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/boxplots.html#beanplot)
Make a bean plot of each dataset in the `data` sequence.
A bean plot is a combination of a `violinplot` (kernel density estimate of the probability density function per point) with a line-scatter plot of all individual data points.
| Parameters: | * **data** (*sequence of ndarrays*) β Data arrays, one array per value in `positions`.
* **ax** (*Matplotlib AxesSubplot instance**,* *optional*) β If given, this subplot is used to plot in instead of a new figure being created.
* **labels** (*list of str**,* *optional*) β Tick labels for the horizontal axis. If not given, integers `1..len(data)` are used.
* **positions** (*array\_like**,* *optional*) β Position array, used as the horizontal axis of the plot. If not given, spacing of the violins will be equidistant.
* **side** (*{'both'**,* *'left'**,* *'right'}**,* *optional*) β How to plot the violin. Default is βbothβ. The βleftβ, βrightβ options can be used to create asymmetric violin plots.
* **jitter** (*bool**,* *optional*) β If True, jitter markers within violin instead of plotting regular lines around the center. This can be useful if the data is very dense.
* **plot\_opts** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,* *optional*) β A dictionary with plotting options. All the options for `violinplot` can be specified, they will simply be passed to `violinplot`. Options specific to `beanplot` are:
+ `βviolin_widthβ : float. Relative width of violins. Max available` space is 1, default is 0.8.
+ βbean\_colorβ, MPL color. Color of bean plot lines. Default is βkβ. Also used for jitter marker edge color if `jitter` is True.
+ βbean\_sizeβ, scalar. Line length as a fraction of maximum length. Default is 0.5.
+ βbean\_lwβ, scalar. Linewidth, default is 0.5.
+ βbean\_show\_meanβ, bool. If True (default), show mean as a line.
+ βbean\_show\_medianβ, bool. If True (default), show median as a marker.
+ βbean\_mean\_colorβ, MPL color. Color of mean line. Default is βbβ.
+ βbean\_mean\_lwβ, scalar. Linewidth of mean line, default is 2.
+ βbean\_mean\_sizeβ, scalar. Line length as a fraction of maximum length. Default is 0.5.
+ βbean\_median\_colorβ, MPL color. Color of median marker. Default is βrβ.
+ βbean\_median\_markerβ, MPL marker. Marker type, default is β+β.
+ `βjitter_markerβ, MPL marker. Marker type for jitter=True.` Default is βoβ.
+ βjitter\_marker\_sizeβ, int. Marker size. Default is 4.
+ βjitter\_fcβ, MPL color. Jitter marker face color. Default is None.
+ βbean\_legend\_textβ, str. If given, add a legend with given text.
|
| Returns: | **fig** β If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. |
| Return type: | Matplotlib figure instance |
See also
[`violinplot`](statsmodels.graphics.boxplots.violinplot#statsmodels.graphics.boxplots.violinplot "statsmodels.graphics.boxplots.violinplot")
Violin plot, also used internally in `beanplot`.
`matplotlib.pyplot.boxplot` Standard boxplot. #### References
P. Kampstra, βBeanplot: A Boxplot Alternative for Visual Comparison of Distributionsβ, J. Stat. Soft., Vol. 28, pp. 1-9, 2008.
#### Examples
We use the American National Election Survey 1996 dataset, which has Party Identification of respondents as independent variable and (among other data) age as dependent variable.
```
>>> data = sm.datasets.anes96.load_pandas()
>>> party_ID = np.arange(7)
>>> labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat",
... "Independent-Indpendent", "Independent-Republican",
... "Weak Republican", "Strong Republican"]
```
Group age by party ID, and create a violin plot with it:
```
>>> plt.rcParams['figure.subplot.bottom'] = 0.23 # keep labels visible
>>> age = [data.exog['age'][data.endog == id] for id in party_ID]
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> sm.graphics.beanplot(age, ax=ax, labels=labels,
... plot_opts={'cutoff_val':5, 'cutoff_type':'abs',
... 'label_fontsize':'small',
... 'label_rotation':30})
>>> ax.set_xlabel("Party identification of respondent.")
>>> ax.set_ylabel("Age")
>>> plt.show()
```
([Source code](../plots/graphics_boxplot_beanplot.py), [png](../plots/graphics_boxplot_beanplot.png), [hires.png](../plots/graphics_boxplot_beanplot.hires.png), [pdf](../plots/graphics_boxplot_beanplot.pdf))
| programming_docs |
statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.prsquared statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.prsquared
===============================================================================
`ZeroInflatedNegativeBinomialResults.prsquared()`
statsmodels statsmodels.imputation.mice.MICEData statsmodels.imputation.mice.MICEData
====================================
`class statsmodels.imputation.mice.MICEData(data, perturbation_method='gaussian', k_pmm=20, history_callback=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData)
Wrap a data set to allow missing data handling with MICE.
| Parameters: | * **data** (*Pandas data frame*) β The data set, whch is copied internally.
* **perturbation\_method** (*string*) β The default perturbation method
* **k\_pmm** (*int*) β The number of nearest neighbors to use during predictive mean matching. Can also be specified in `fit`.
* **history\_callback** (*function*) β A function that is called after each complete imputation cycle. The return value is appended to `history`. The MICEData object is passed as the sole argument to `history_callback`.
|
#### Examples
Draw 20 imputations from a data set called `data` and save them in separate files with filename pattern `dataXX.csv`. The variables other than `x1` are imputed using linear models fit with OLS, with mean structures containing main effects of all other variables in `data`. The variable named `x1` has a condtional mean structure that includes an additional term for x2^2.
```
>>> imp = mice.MICEData(data)
>>> imp.set_imputer('x1', formula='x2 + np.square(x2) + x3')
>>> for j in range(20):
... imp.update_all()
... imp.data.to_csv('data%02d.csv' % j)
```
Impute using default models, using the MICEData object as an iterator.
```
>>> imp = mice.MICEData(data)
>>> j = 0
>>> for data in imp:
... imp.data.to_csv('data%02d.csv' % j)
... j += 1
```
#### Notes
Allowed perturbation methods are βgaussianβ (the model parameters are set to a draw from the Gaussian approximation to the posterior distribution), and βbootβ (the model parameters are set to the estimated values obtained when fitting a bootstrapped version of the data set).
`history_callback` can be implemented to have side effects such as saving the current imputed data set to disk.
#### Methods
| | |
| --- | --- |
| [`get_fitting_data`](statsmodels.imputation.mice.micedata.get_fitting_data#statsmodels.imputation.mice.MICEData.get_fitting_data "statsmodels.imputation.mice.MICEData.get_fitting_data")(vname) | Return the data needed to fit a model for imputation. |
| [`get_split_data`](statsmodels.imputation.mice.micedata.get_split_data#statsmodels.imputation.mice.MICEData.get_split_data "statsmodels.imputation.mice.MICEData.get_split_data")(vname) | Return endog and exog for imputation of a given variable. |
| [`impute`](statsmodels.imputation.mice.micedata.impute#statsmodels.imputation.mice.MICEData.impute "statsmodels.imputation.mice.MICEData.impute")(vname) | |
| [`impute_pmm`](statsmodels.imputation.mice.micedata.impute_pmm#statsmodels.imputation.mice.MICEData.impute_pmm "statsmodels.imputation.mice.MICEData.impute_pmm")(vname) | Use predictive mean matching to impute missing values. |
| [`next_sample`](statsmodels.imputation.mice.micedata.next_sample#statsmodels.imputation.mice.MICEData.next_sample "statsmodels.imputation.mice.MICEData.next_sample")() | Returns the next imputed dataset in the imputation process. |
| [`perturb_params`](statsmodels.imputation.mice.micedata.perturb_params#statsmodels.imputation.mice.MICEData.perturb_params "statsmodels.imputation.mice.MICEData.perturb_params")(vname) | |
| [`plot_bivariate`](statsmodels.imputation.mice.micedata.plot_bivariate#statsmodels.imputation.mice.MICEData.plot_bivariate "statsmodels.imputation.mice.MICEData.plot_bivariate")(col1\_name, col2\_name[, β¦]) | Plot observed and imputed values for two variables. |
| [`plot_fit_obs`](statsmodels.imputation.mice.micedata.plot_fit_obs#statsmodels.imputation.mice.MICEData.plot_fit_obs "statsmodels.imputation.mice.MICEData.plot_fit_obs")(col\_name[, lowess\_args, β¦]) | Plot fitted versus imputed or observed values as a scatterplot. |
| [`plot_imputed_hist`](statsmodels.imputation.mice.micedata.plot_imputed_hist#statsmodels.imputation.mice.MICEData.plot_imputed_hist "statsmodels.imputation.mice.MICEData.plot_imputed_hist")(col\_name[, ax, β¦]) | Display imputed values for one variable as a histogram. |
| [`plot_missing_pattern`](statsmodels.imputation.mice.micedata.plot_missing_pattern#statsmodels.imputation.mice.MICEData.plot_missing_pattern "statsmodels.imputation.mice.MICEData.plot_missing_pattern")([ax, row\_order, β¦]) | Generate an image showing the missing data pattern. |
| [`set_imputer`](statsmodels.imputation.mice.micedata.set_imputer#statsmodels.imputation.mice.MICEData.set_imputer "statsmodels.imputation.mice.MICEData.set_imputer")(endog\_name[, formula, β¦]) | Specify the imputation process for a single variable. |
| [`update`](statsmodels.imputation.mice.micedata.update#statsmodels.imputation.mice.MICEData.update "statsmodels.imputation.mice.MICEData.update")(vname) | Impute missing values for a single variable. |
| [`update_all`](statsmodels.imputation.mice.micedata.update_all#statsmodels.imputation.mice.MICEData.update_all "statsmodels.imputation.mice.MICEData.update_all")([n\_iter]) | Perform a specified number of MICE iterations. |
statsmodels statsmodels.sandbox.stats.multicomp.StepDown.stepdown statsmodels.sandbox.stats.multicomp.StepDown.stepdown
=====================================================
`StepDown.stepdown(indices)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#StepDown.stepdown)
statsmodels statsmodels.discrete.discrete_model.DiscreteModel.cdf statsmodels.discrete.discrete\_model.DiscreteModel.cdf
======================================================
`DiscreteModel.cdf(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteModel.cdf)
The cumulative distribution function of the model.
statsmodels statsmodels.discrete.count_model.GenericZeroInflated.cdf statsmodels.discrete.count\_model.GenericZeroInflated.cdf
=========================================================
`GenericZeroInflated.cdf(X)`
The cumulative distribution function of the model.
statsmodels statsmodels.tsa.filters.filtertools.recursive_filter statsmodels.tsa.filters.filtertools.recursive\_filter
=====================================================
`statsmodels.tsa.filters.filtertools.recursive_filter(x, ar_coeff, init=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/filters/filtertools.html#recursive_filter)
Autoregressive, or recursive, filtering.
| Parameters: | * **x** (*array-like*) β Time-series data. Should be 1d or n x 1.
* **ar\_coeff** (*array-like*) β AR coefficients in reverse time order. See Notes
* **init** (*array-like*) β Initial values of the time-series prior to the first value of y. The default is zero.
|
| Returns: | **y** β Filtered array, number of columns determined by x and ar\_coeff. If a pandas object is given, a pandas object is returned. |
| Return type: | array |
#### Notes
Computes the recursive filter
```
y[n] = ar_coeff[0] * y[n-1] + ...
+ ar_coeff[n_coeff - 1] * y[n - n_coeff] + x[n]
```
where n\_coeff = len(n\_coeff).
statsmodels statsmodels.stats.power.zt_ind_solve_power statsmodels.stats.power.zt\_ind\_solve\_power
=============================================
`statsmodels.stats.power.zt_ind_solve_power = <bound method NormalIndPower.solve_power of <statsmodels.stats.power.NormalIndPower object>>`
solve for any one parameter of the power of a two sample z-test
for z-test the keywords are: effect\_size, nobs1, alpha, power, ratio exactly one needs to be `None`, all others need numeric values
| Parameters: | * **effect\_size** (*float*) β standardized effect size, difference between the two means divided by the standard deviation. If ratio=0, then this is the standardized mean in the one sample test.
* **nobs1** (*int* *or* *float*) β number of observations of sample 1. The number of observations of sample two is ratio times the size of sample 1, i.e. `nobs2 = nobs1 * ratio` `ratio` can be set to zero in order to get the power for a one sample test.
* **alpha** (*float in interval* *(**0**,**1**)*) β significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true.
* **power** (*float in interval* *(**0**,**1**)*) β power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true.
* **ratio** (*float*) β ratio of the number of observations in sample 2 relative to sample 1. see description of nobs1 The default for ratio is 1; to solve for ration given the other arguments it has to be explicitly set to None.
* **alternative** (*string**,* *'two-sided'* *(**default**)**,* *'larger'**,* *'smaller'*) β extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. The one-sided test can be either βlargerβ, βsmallerβ.
|
| Returns: | **value** β The value of the parameter that was set to None in the call. The value solves the power equation given the remaining parameters. |
| Return type: | float |
#### Notes
The function uses scipy.optimize for finding the value that satisfies the power equation. It first uses `brentq` with a prior search for bounds. If this fails to find a root, `fsolve` is used. If `fsolve` also fails, then, for `alpha`, `power` and `effect_size`, `brentq` with fixed bounds is used. However, there can still be cases where this fails.
statsmodels statsmodels.regression.linear_model.GLS.hessian_factor statsmodels.regression.linear\_model.GLS.hessian\_factor
========================================================
`GLS.hessian_factor(params, scale=None, observed=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#GLS.hessian_factor)
Weights for calculating Hessian
| Parameters: | * **params** (*ndarray*) β parameter at which Hessian is evaluated
* **scale** (*None* *or* *float*) β If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale.
* **observed** (*bool*) β If True, then the observed Hessian is returned. If false then the expected information matrix is returned.
|
| Returns: | **hessian\_factor** β A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` |
| Return type: | ndarray, 1d |
statsmodels statsmodels.graphics.gofplots.ProbPlot.theoretical_quantiles statsmodels.graphics.gofplots.ProbPlot.theoretical\_quantiles
=============================================================
`ProbPlot.theoretical_quantiles()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#ProbPlot.theoretical_quantiles)
statsmodels statsmodels.robust.norms.TrimmedMean.psi_deriv statsmodels.robust.norms.TrimmedMean.psi\_deriv
===============================================
`TrimmedMean.psi_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#TrimmedMean.psi_deriv)
The derivative of least trimmed mean psi function
#### Notes
Used to estimate the robust covariance matrix.
statsmodels statsmodels.emplike.descriptive.DescStatUV.test_joint_skew_kurt statsmodels.emplike.descriptive.DescStatUV.test\_joint\_skew\_kurt
==================================================================
`DescStatUV.test_joint_skew_kurt(skew0, kurt0, return_weights=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV.test_joint_skew_kurt)
Returns - 2 x log-likelihood and the p-value for the joint hypothesis test for skewness and kurtosis
| Parameters: | * **skew0** (*float*) β Skewness value to be tested
* **kurt0** (*float*) β Kurtosis value to be tested
* **return\_weights** (*bool*) β If True, function also returns the weights that maximize the likelihood ratio. Default is False.
|
| Returns: | **test\_results** β The log-likelihood ratio and p-value of the joint hypothesis test. |
| Return type: | tuple |
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.normalized_cov_params statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.normalized\_cov\_params
=======================================================================================
`DynamicFactorResults.normalized_cov_params()`
statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.lnalpha statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.lnalpha
======================================================================
`GeneralizedPoissonResults.lnalpha()`
statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.plot_ceres_residuals statsmodels.genmod.generalized\_linear\_model.GLMResults.plot\_ceres\_residuals
===============================================================================
`GLMResults.plot_ceres_residuals(focus_exog, frac=0.66, cond_means=None, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.plot_ceres_residuals)
Produces a CERES (Conditional Expectation Partial Residuals) plot for a fitted regression model.
| Parameters: | * **focus\_exog** (*integer* *or* *string*) β The column index of results.model.exog, or the variable name, indicating the variable whose role in the regression is to be assessed.
* **frac** (*float*) β Lowess tuning parameter for the adjusted model used in the CERES analysis. Not used if `cond_means` is provided.
* **cond\_means** (*array-like**,* *optional*) β If provided, the columns of this array span the space of the conditional means E[exog | focus exog], where exog ranges over some or all of the columns of exog (other than the focus exog).
* **ax** (*matplotlib.Axes instance**,* *optional*) β The axes on which to draw the plot. If not provided, a new axes instance is created.
|
| Returns: | **fig** β The figure on which the partial residual plot is drawn. |
| Return type: | matplotlib.Figure instance |
#### References
RD Cook and R Croos-Dabrera (1998). Partial residual plots in generalized linear models. Journal of the American Statistical Association, 93:442.
RD Cook (1993). Partial residual plots. Technometrics 35:4.
#### Notes
`cond_means` is intended to capture the behavior of E[x1 | x2], where x2 is the focus exog and x1 are all the other exog variables. If all the conditional mean relationships are linear, it is sufficient to set cond\_means equal to the focus exog. Alternatively, cond\_means may consist of one or more columns containing functional transformations of the focus exog (e.g. x2^2) that are thought to capture E[x1 | x2].
If nothing is known or suspected about the form of E[x1 | x2], set `cond_means` to None, and it will be estimated by smoothing each non-focus exog against the focus exog. The values of `frac` control these lowess smooths.
If cond\_means contains only the focus exog, the results are equivalent to a partial residual plot.
If the focus variable is believed to be independent of the other exog variables, `cond_means` can be set to an (empty) nx0 array.
statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.eigenvals statsmodels.sandbox.regression.gmm.IVRegressionResults.eigenvals
================================================================
`IVRegressionResults.eigenvals()`
Return eigenvalues sorted in decreasing order.
statsmodels statsmodels.tools.tools.categorical statsmodels.tools.tools.categorical
===================================
`statsmodels.tools.tools.categorical(data, col=None, dictnames=False, drop=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/tools.html#categorical)
Returns a dummy matrix given an array of categorical variables.
| Parameters: | * **data** (*array*) β A structured array, recarray, or array. This can be either a 1d vector of the categorical variable or a 2d array with the column specifying the categorical variable specified by the col argument.
* **col** (*'string'**,* *int**, or* *None*) β If data is a structured array or a recarray, `col` can be a string that is the name of the column that contains the variable. For all arrays `col` can be an int that is the (zero-based) column index number. `col` can only be None for a 1d array. The default is None.
* **dictnames** (*bool**,* *optional*) β If True, a dictionary mapping the column number to the categorical name is returned. Used to have information about plain arrays.
* **drop** (*bool*) β Whether or not keep the categorical variable in the returned matrix.
|
| Returns: | A matrix of dummy (indicator/binary) float variables for the categorical data. If dictnames is True, then the dictionary is returned as well. |
| Return type: | dummy\_matrix, [dictnames, optional] |
#### Notes
This returns a dummy variable for EVERY distinct variable. If a a structured or recarray is provided, the names for the new variable is the old variable name - underscore - category name. So if the a variable βvoteβ had answers as βyesβ or βnoβ then the returned array would have to new variablesβ βvote\_yesβ and βvote\_noβ. There is currently no name checking.
#### Examples
```
>>> import numpy as np
>>> import statsmodels.api as sm
```
Univariate examples
```
>>> import string
>>> string_var = [string.ascii_lowercase[0:5], string.ascii_lowercase[5:10], string.ascii_lowercase[10:15], string.ascii_lowercase[15:20], string.ascii_lowercase[20:25]]
>>> string_var *= 5
>>> string_var = np.asarray(sorted(string_var))
>>> design = sm.tools.categorical(string_var, drop=True)
```
Or for a numerical categorical variable
```
>>> instr = np.floor(np.arange(10,60, step=2)/10)
>>> design = sm.tools.categorical(instr, drop=True)
```
With a structured array
```
>>> num = np.random.randn(25,2)
>>> struct_ar = np.zeros((25,1), dtype=[('var1', 'f4'),('var2', 'f4'), ('instrument','f4'),('str_instr','a5')])
>>> struct_ar['var1'] = num[:,0][:,None]
>>> struct_ar['var2'] = num[:,1][:,None]
>>> struct_ar['instrument'] = instr[:,None]
>>> struct_ar['str_instr'] = string_var[:,None]
>>> design = sm.tools.categorical(struct_ar, col='instrument', drop=True)
```
Or
```
>>> design2 = sm.tools.categorical(struct_ar, col='str_instr', drop=True)
```
statsmodels statsmodels.genmod.families.family.NegativeBinomial.weights statsmodels.genmod.families.family.NegativeBinomial.weights
===========================================================
`NegativeBinomial.weights(mu)`
Weights for IRLS steps
| Parameters: | **mu** (*array-like*) β The transformed mean response variable in the exponential family |
| Returns: | **w** β The weights for the IRLS steps |
| Return type: | array |
#### Notes
\[w = 1 / (g'(\mu)^2 \* Var(\mu))\]
statsmodels statsmodels.discrete.discrete_model.DiscreteResults.remove_data statsmodels.discrete.discrete\_model.DiscreteResults.remove\_data
=================================================================
`DiscreteResults.remove_data()`
remove data arrays, all nobs arrays from result and model
This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.
Warning
Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.
Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.
The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data.
The attributes to remove are named in:
`model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name.
`result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name)
`result._data_attr_model : arrays attached to the model` instance but not to the results instance
| programming_docs |
statsmodels statsmodels.robust.robust_linear_model.RLMResults.remove_data statsmodels.robust.robust\_linear\_model.RLMResults.remove\_data
================================================================
`RLMResults.remove_data()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLMResults.remove_data)
remove data arrays, all nobs arrays from result and model
This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.
Warning
Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.
Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.
The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data.
The attributes to remove are named in:
`model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name.
`result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name)
`result._data_attr_model : arrays attached to the model` instance but not to the results instance
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.hessian statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.hessian
================================================================
`DynamicFactor.hessian(params, *args, **kwargs)`
Hessian matrix of the likelihood function, evaluated at the given parameters
| Parameters: | * **params** (*array\_like*) β Array of parameters at which to evaluate the hessian.
* **args** β Additional positional arguments to the `loglike` method.
* **kwargs** β Additional keyword arguments to the `loglike` method.
|
| Returns: | **hessian** β Hessian matrix evaluated at `params` |
| Return type: | array |
#### Notes
This is a numerical approximation.
Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`).
statsmodels statsmodels.regression.mixed_linear_model.MixedLM.score_sqrt statsmodels.regression.mixed\_linear\_model.MixedLM.score\_sqrt
===============================================================
`MixedLM.score_sqrt(params, calc_fe=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.score_sqrt)
Returns the score with respect to transformed parameters.
Calculates the score vector with respect to the parameterization in which the random effects covariance matrix is represented through its Cholesky square root.
| Parameters: | * **params** (*MixedLMParams* *or* *array-like*) β The model parameters. If array-like must contain packed parameters that are compatible with this model instance.
* **calc\_fe** (*boolean*) β If True, calculate the score vector for the fixed effects parameters. If False, this vector is not calculated, and a vector of zeros is returned in its place.
|
| Returns: | * **score\_fe** (*array-like*) β The score vector with respect to the fixed effects parameters.
* **score\_re** (*array-like*) β The score vector with respect to the random effects parameters (excluding variance components parameters).
* **score\_vc** (*array-like*) β The score vector with respect to variance components parameters.
|
statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.to_vecm statsmodels.tsa.vector\_ar.var\_model.VARProcess.to\_vecm
=========================================================
`VARProcess.to_vecm()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.to_vecm)
statsmodels statsmodels.regression.linear_model.GLS.initialize statsmodels.regression.linear\_model.GLS.initialize
===================================================
`GLS.initialize()`
Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed.
statsmodels statsmodels.stats.weightstats.DescrStatsW.std statsmodels.stats.weightstats.DescrStatsW.std
=============================================
`DescrStatsW.std()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.std)
standard deviation with default degrees of freedom correction
statsmodels statsmodels.stats.power.NormalIndPower.solve_power statsmodels.stats.power.NormalIndPower.solve\_power
===================================================
`NormalIndPower.solve_power(effect_size=None, nobs1=None, alpha=None, power=None, ratio=1.0, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#NormalIndPower.solve_power)
solve for any one parameter of the power of a two sample z-test
for z-test the keywords are: effect\_size, nobs1, alpha, power, ratio exactly one needs to be `None`, all others need numeric values
| Parameters: | * **effect\_size** (*float*) β standardized effect size, difference between the two means divided by the standard deviation. If ratio=0, then this is the standardized mean in the one sample test.
* **nobs1** (*int* *or* *float*) β number of observations of sample 1. The number of observations of sample two is ratio times the size of sample 1, i.e. `nobs2 = nobs1 * ratio` `ratio` can be set to zero in order to get the power for a one sample test.
* **alpha** (*float in interval* *(**0**,**1**)*) β significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true.
* **power** (*float in interval* *(**0**,**1**)*) β power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true.
* **ratio** (*float*) β ratio of the number of observations in sample 2 relative to sample 1. see description of nobs1 The default for ratio is 1; to solve for ration given the other arguments it has to be explicitly set to None.
* **alternative** (*string**,* *'two-sided'* *(**default**)**,* *'larger'**,* *'smaller'*) β extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. The one-sided test can be either βlargerβ, βsmallerβ.
|
| Returns: | **value** β The value of the parameter that was set to None in the call. The value solves the power equation given the remaining parameters. |
| Return type: | float |
#### Notes
The function uses scipy.optimize for finding the value that satisfies the power equation. It first uses `brentq` with a prior search for bounds. If this fails to find a root, `fsolve` is used. If `fsolve` also fails, then, for `alpha`, `power` and `effect_size`, `brentq` with fixed bounds is used. However, there can still be cases where this fails.
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.zvalues statsmodels.tsa.statespace.structural.UnobservedComponentsResults.zvalues
=========================================================================
`UnobservedComponentsResults.zvalues()`
(array) The z-statistics for the coefficients.
statsmodels statsmodels.stats.weightstats._tstat_generic statsmodels.stats.weightstats.\_tstat\_generic
==============================================
`statsmodels.stats.weightstats._tstat_generic(value1, value2, std_diff, dof, alternative, diff=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#_tstat_generic)
generic ttest to save typing
statsmodels statsmodels.tsa.statespace.varmax.VARMAX.observed_information_matrix statsmodels.tsa.statespace.varmax.VARMAX.observed\_information\_matrix
======================================================================
`VARMAX.observed_information_matrix(params, transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)`
Observed information matrix
| Parameters: | * **params** (*array\_like**,* *optional*) β Array of parameters at which to evaluate the loglikelihood function.
* **\*\*kwargs** β Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details.
|
#### Notes
This method is from Harvey (1989), which shows that the information matrix only depends on terms from the gradient. This implementation is partially analytic and partially numeric approximation, therefore, because it uses the analytic formula for the information matrix, with numerically computed elements of the gradient.
#### References
Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press.
statsmodels statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter.T statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter.T
===================================================
`classmethod KalmanFilter.T(params, r, k, p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/kalmanf/kalmanfilter.html#KalmanFilter.T)
The coefficient matrix for the state vector in the state equation.
Its dimension is r+k x r+k.
| Parameters: | * **r** (*int*) β In the context of the ARMA model r is max(p,q+1) where p is the AR order and q is the MA order.
* **k** (*int*) β The number of exogenous variables in the ARMA model, including the constant if appropriate.
* **p** (*int*) β The AR coefficient in an ARMA model.
|
#### References
Durbin and Koopman Section 3.7.
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.t\_test
===============================================================================
`ZeroInflatedGeneralizedPoissonResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)`
Compute a t-test for a each linear hypothesis of the form Rb = q
| Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) β
+ array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β An optional `scale` to use. Default is the scale specified by the model fit.
* **use\_t** (*bool**,* *optional*) β If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution.
|
| Returns: | **res** β The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. |
| Return type: | ContrastResults instance |
#### Examples
```
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> r = np.zeros_like(results.params)
>>> r[5:] = [1,-1]
>>> print(r)
[ 0. 0. 0. 0. 0. 1. -1.]
```
r tests that the coefficients on the 5th and 6th independent variable are the same.
```
>>> T_test = results.t_test(r)
>>> print(T_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037
==============================================================================
>>> T_test.effect
-1829.2025687192481
>>> T_test.sd
455.39079425193762
>>> T_test.tvalue
-4.0167754636411717
>>> T_test.pvalue
0.0015163772380899498
```
Alternatively, you can specify the hypothesis tests using a string
```
>>> from statsmodels.formula.api import ols
>>> dta = sm.datasets.longley.load_pandas().data
>>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR'
>>> results = ols(formula, dta).fit()
>>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1'
>>> t_test = results.t_test(hypotheses)
>>> print(t_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 15.0977 84.937 0.178 0.863 -177.042 207.238
c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915
c2 1.0001 0.249 0.000 1.000 0.437 1.563
==============================================================================
```
See also
[`tvalues`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.tvalues#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.tvalues "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.tvalues")
individual t statistics
[`f_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.f_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.f_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.f_test")
for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults statsmodels.discrete.discrete\_model.NegativeBinomialResults
============================================================
`class statsmodels.discrete.discrete_model.NegativeBinomialResults(model, mlefit, cov_type='nonrobust', cov_kwds=None, use_t=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomialResults)
A results class for NegativeBinomial 1 and 2
| Parameters: | * **model** (*A DiscreteModel instance*) β
* **params** (*array-like*) β The parameters of a fitted model.
* **hessian** (*array-like*) β The hessian of the fitted model.
* **scale** (*float*) β A scale parameter for the covariance matrix.
|
| Returns: | * *\*Attributes\**
* **aic** (*float*) β Akaike information criterion. `-2*(llf - p)` where `p` is the number of regressors including the intercept.
* **bic** (*float*) β Bayesian information criterion. `-2*llf + ln(nobs)*p` where `p` is the number of regressors including the intercept.
* **bse** (*array*) β The standard errors of the coefficients.
* **df\_resid** (*float*) β See model definition.
* **df\_model** (*float*) β See model definition.
* **fitted\_values** (*array*) β Linear predictor XB.
* **llf** (*float*) β Value of the loglikelihood
* **llnull** (*float*) β Value of the constant-only loglikelihood
* **llr** (*float*) β Likelihood ratio chi-squared statistic; `-2*(llnull - llf)`
* **llr\_pvalue** (*float*) β The chi-squared probability of getting a log-likelihood ratio statistic greater than llr. llr has a chi-squared distribution with degrees of freedom `df_model`.
* **prsquared** (*float*) β McFaddenβs pseudo-R-squared. `1 - (llf / llnull)`
|
#### Methods
| | |
| --- | --- |
| [`aic`](statsmodels.discrete.discrete_model.negativebinomialresults.aic#statsmodels.discrete.discrete_model.NegativeBinomialResults.aic "statsmodels.discrete.discrete_model.NegativeBinomialResults.aic")() | |
| [`bic`](statsmodels.discrete.discrete_model.negativebinomialresults.bic#statsmodels.discrete.discrete_model.NegativeBinomialResults.bic "statsmodels.discrete.discrete_model.NegativeBinomialResults.bic")() | |
| [`bse`](statsmodels.discrete.discrete_model.negativebinomialresults.bse#statsmodels.discrete.discrete_model.NegativeBinomialResults.bse "statsmodels.discrete.discrete_model.NegativeBinomialResults.bse")() | |
| [`conf_int`](statsmodels.discrete.discrete_model.negativebinomialresults.conf_int#statsmodels.discrete.discrete_model.NegativeBinomialResults.conf_int "statsmodels.discrete.discrete_model.NegativeBinomialResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. |
| [`cov_params`](statsmodels.discrete.discrete_model.negativebinomialresults.cov_params#statsmodels.discrete.discrete_model.NegativeBinomialResults.cov_params "statsmodels.discrete.discrete_model.NegativeBinomialResults.cov_params")([r\_matrix, column, scale, cov\_p, β¦]) | Returns the variance/covariance matrix. |
| [`f_test`](statsmodels.discrete.discrete_model.negativebinomialresults.f_test#statsmodels.discrete.discrete_model.NegativeBinomialResults.f_test "statsmodels.discrete.discrete_model.NegativeBinomialResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. |
| [`fittedvalues`](statsmodels.discrete.discrete_model.negativebinomialresults.fittedvalues#statsmodels.discrete.discrete_model.NegativeBinomialResults.fittedvalues "statsmodels.discrete.discrete_model.NegativeBinomialResults.fittedvalues")() | |
| [`get_margeff`](statsmodels.discrete.discrete_model.negativebinomialresults.get_margeff#statsmodels.discrete.discrete_model.NegativeBinomialResults.get_margeff "statsmodels.discrete.discrete_model.NegativeBinomialResults.get_margeff")([at, method, atexog, dummy, count]) | Get marginal effects of the fitted model. |
| [`initialize`](statsmodels.discrete.discrete_model.negativebinomialresults.initialize#statsmodels.discrete.discrete_model.NegativeBinomialResults.initialize "statsmodels.discrete.discrete_model.NegativeBinomialResults.initialize")(model, params, \*\*kwd) | |
| [`llf`](statsmodels.discrete.discrete_model.negativebinomialresults.llf#statsmodels.discrete.discrete_model.NegativeBinomialResults.llf "statsmodels.discrete.discrete_model.NegativeBinomialResults.llf")() | |
| [`llnull`](statsmodels.discrete.discrete_model.negativebinomialresults.llnull#statsmodels.discrete.discrete_model.NegativeBinomialResults.llnull "statsmodels.discrete.discrete_model.NegativeBinomialResults.llnull")() | |
| [`llr`](statsmodels.discrete.discrete_model.negativebinomialresults.llr#statsmodels.discrete.discrete_model.NegativeBinomialResults.llr "statsmodels.discrete.discrete_model.NegativeBinomialResults.llr")() | |
| [`llr_pvalue`](statsmodels.discrete.discrete_model.negativebinomialresults.llr_pvalue#statsmodels.discrete.discrete_model.NegativeBinomialResults.llr_pvalue "statsmodels.discrete.discrete_model.NegativeBinomialResults.llr_pvalue")() | |
| [`lnalpha`](statsmodels.discrete.discrete_model.negativebinomialresults.lnalpha#statsmodels.discrete.discrete_model.NegativeBinomialResults.lnalpha "statsmodels.discrete.discrete_model.NegativeBinomialResults.lnalpha")() | |
| [`lnalpha_std_err`](statsmodels.discrete.discrete_model.negativebinomialresults.lnalpha_std_err#statsmodels.discrete.discrete_model.NegativeBinomialResults.lnalpha_std_err "statsmodels.discrete.discrete_model.NegativeBinomialResults.lnalpha_std_err")() | |
| [`load`](statsmodels.discrete.discrete_model.negativebinomialresults.load#statsmodels.discrete.discrete_model.NegativeBinomialResults.load "statsmodels.discrete.discrete_model.NegativeBinomialResults.load")(fname) | load a pickle, (class method) |
| [`normalized_cov_params`](statsmodels.discrete.discrete_model.negativebinomialresults.normalized_cov_params#statsmodels.discrete.discrete_model.NegativeBinomialResults.normalized_cov_params "statsmodels.discrete.discrete_model.NegativeBinomialResults.normalized_cov_params")() | |
| [`predict`](statsmodels.discrete.discrete_model.negativebinomialresults.predict#statsmodels.discrete.discrete_model.NegativeBinomialResults.predict "statsmodels.discrete.discrete_model.NegativeBinomialResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. |
| [`prsquared`](statsmodels.discrete.discrete_model.negativebinomialresults.prsquared#statsmodels.discrete.discrete_model.NegativeBinomialResults.prsquared "statsmodels.discrete.discrete_model.NegativeBinomialResults.prsquared")() | |
| [`pvalues`](statsmodels.discrete.discrete_model.negativebinomialresults.pvalues#statsmodels.discrete.discrete_model.NegativeBinomialResults.pvalues "statsmodels.discrete.discrete_model.NegativeBinomialResults.pvalues")() | |
| [`remove_data`](statsmodels.discrete.discrete_model.negativebinomialresults.remove_data#statsmodels.discrete.discrete_model.NegativeBinomialResults.remove_data "statsmodels.discrete.discrete_model.NegativeBinomialResults.remove_data")() | remove data arrays, all nobs arrays from result and model |
| [`resid`](statsmodels.discrete.discrete_model.negativebinomialresults.resid#statsmodels.discrete.discrete_model.NegativeBinomialResults.resid "statsmodels.discrete.discrete_model.NegativeBinomialResults.resid")() | Residuals |
| [`save`](statsmodels.discrete.discrete_model.negativebinomialresults.save#statsmodels.discrete.discrete_model.NegativeBinomialResults.save "statsmodels.discrete.discrete_model.NegativeBinomialResults.save")(fname[, remove\_data]) | save a pickle of this instance |
| [`set_null_options`](statsmodels.discrete.discrete_model.negativebinomialresults.set_null_options#statsmodels.discrete.discrete_model.NegativeBinomialResults.set_null_options "statsmodels.discrete.discrete_model.NegativeBinomialResults.set_null_options")([llnull, attach\_results]) | set fit options for Null (constant-only) model |
| [`summary`](statsmodels.discrete.discrete_model.negativebinomialresults.summary#statsmodels.discrete.discrete_model.NegativeBinomialResults.summary "statsmodels.discrete.discrete_model.NegativeBinomialResults.summary")([yname, xname, title, alpha, yname\_list]) | Summarize the Regression Results |
| [`summary2`](statsmodels.discrete.discrete_model.negativebinomialresults.summary2#statsmodels.discrete.discrete_model.NegativeBinomialResults.summary2 "statsmodels.discrete.discrete_model.NegativeBinomialResults.summary2")([yname, xname, title, alpha, β¦]) | Experimental function to summarize regression results |
| [`t_test`](statsmodels.discrete.discrete_model.negativebinomialresults.t_test#statsmodels.discrete.discrete_model.NegativeBinomialResults.t_test "statsmodels.discrete.discrete_model.NegativeBinomialResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q |
| [`t_test_pairwise`](statsmodels.discrete.discrete_model.negativebinomialresults.t_test_pairwise#statsmodels.discrete.discrete_model.NegativeBinomialResults.t_test_pairwise "statsmodels.discrete.discrete_model.NegativeBinomialResults.t_test_pairwise")(term\_name[, method, alpha, β¦]) | perform pairwise t\_test with multiple testing corrected p-values |
| [`tvalues`](statsmodels.discrete.discrete_model.negativebinomialresults.tvalues#statsmodels.discrete.discrete_model.NegativeBinomialResults.tvalues "statsmodels.discrete.discrete_model.NegativeBinomialResults.tvalues")() | Return the t-statistic for a given parameter estimate. |
| [`wald_test`](statsmodels.discrete.discrete_model.negativebinomialresults.wald_test#statsmodels.discrete.discrete_model.NegativeBinomialResults.wald_test "statsmodels.discrete.discrete_model.NegativeBinomialResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, β¦]) | Compute a Wald-test for a joint linear hypothesis. |
| [`wald_test_terms`](statsmodels.discrete.discrete_model.negativebinomialresults.wald_test_terms#statsmodels.discrete.discrete_model.NegativeBinomialResults.wald_test_terms "statsmodels.discrete.discrete_model.NegativeBinomialResults.wald_test_terms")([skip\_single, β¦]) | Compute a sequence of Wald tests for terms over multiple columns |
#### Attributes
| | |
| --- | --- |
| `use_t` | |
| programming_docs |
statsmodels statsmodels.tsa.arima_model.ARMA.from_formula statsmodels.tsa.arima\_model.ARMA.from\_formula
===============================================
`classmethod ARMA.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA.from_formula)
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
statsmodels statsmodels.tsa.ar_model.ARResults.save statsmodels.tsa.ar\_model.ARResults.save
========================================
`ARResults.save(fname, remove_data=False)`
save a pickle of this instance
| Parameters: | * **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle.
* **remove\_data** (*bool*) β If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None.
|
#### Notes
If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception.
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.predict statsmodels.tsa.statespace.structural.UnobservedComponents.predict
==================================================================
`UnobservedComponents.predict(params, exog=None, *args, **kwargs)`
After a model has been fit predict returns the fitted values.
This is a placeholder intended to be overwritten by individual models.
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.predict statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.predict
====================================================================
`ZeroInflatedPoissonResults.predict(exog=None, transform=True, *args, **kwargs)`
Call self.model.predict with self.params as the first argument.
| Parameters: | * **exog** (*array-like**,* *optional*) β The values for which you want to predict. see Notes below.
* **transform** (*bool**,* *optional*) β If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, youβd need to log the data first.
* **kwargs** (*args**,*) β Some models can take additional arguments or keywords, see the predict method of the model for the details.
|
| Returns: | **prediction** β See self.model.predict |
| Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") |
#### Notes
The types of exog that are supported depends on whether a formula was used in the specification of the model.
If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object.
If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array.
Row indices as in pandas data frames are supported, and added to the returned prediction.
statsmodels statsmodels.discrete.discrete_model.CountResults.llr_pvalue statsmodels.discrete.discrete\_model.CountResults.llr\_pvalue
=============================================================
`CountResults.llr_pvalue()`
statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.lnalpha_std_err statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.lnalpha\_std\_err
================================================================================
`GeneralizedPoissonResults.lnalpha_std_err()`
statsmodels statsmodels.regression.quantile_regression.QuantReg.predict statsmodels.regression.quantile\_regression.QuantReg.predict
============================================================
`QuantReg.predict(params, exog=None)`
Return linear predicted values from a design matrix.
| Parameters: | * **params** (*array-like*) β Parameters of a linear model
* **exog** (*array-like**,* *optional.*) β Design / exogenous data. Model exog is used if None.
|
| Returns: | |
| Return type: | An array of fitted values |
#### Notes
If the model has not yet been fit, params is not optional.
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults statsmodels.tsa.vector\_ar.var\_model.VARResults
================================================
`class statsmodels.tsa.vector_ar.var_model.VARResults(endog, endog_lagged, params, sigma_u, lag_order, model=None, trend='c', names=None, dates=None, exog=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults)
Estimate VAR(p) process with fixed number of lags
| Parameters: | * **endog** (*array*) β
* **endog\_lagged** (*array*) β
* **params** (*array*) β
* **sigma\_u** (*array*) β
* **lag\_order** (*int*) β
* **model** (*VAR model instance*) β
* **trend** (*str {'nc'**,* *'c'**,* *'ct'}*) β
* **names** (*array-like*) β List of names of the endogenous variables in order of appearance in `endog`.
* **dates** β
* **exog** (*array*) β
|
| Returns: | * *\*\*Attributes\*\**
* *aic*
* *bic*
* *bse*
* **coefs** (*ndarray (p x K x K)*) β Estimated A\_i matrices, A\_i = coefs[i-1]
* *cov\_params*
* *dates*
* *detomega*
* **df\_model** (*int*)
* **df\_resid** (*int*)
* *endog*
* *endog\_lagged*
* *fittedvalues*
* *fpe*
* *intercept*
* *info\_criteria*
* **k\_ar** (*int*)
* **k\_trend** (*int*)
* *llf*
* *model*
* *names*
* **neqs** (*int*) β Number of variables (equations)
* **nobs** (*int*)
* **n\_totobs** (*int*)
* *params*
* **k\_ar** (*int*) β Order of VAR process
* **params** (*ndarray (Kp + 1) x K*) β A\_i matrices and intercept in stacked form [int A\_1 β¦ A\_p]
* *pvalues*
* **names** (*list*) β variables names
* *resid*
* **roots** (*array*) β The roots of the VAR process are the solution to (I - coefs[0]\*z - coefs[1]\*z\*\*2 β¦ - coefs[p-1]\*z\*\*k\_ar) = 0. Note that the inverse roots are returned, and stability requires that the roots lie outside the unit circle.
* **sigma\_u** (*ndarray (K x K)*) β Estimate of white noise process variance Var[u\_t]
* *sigma\_u\_mle*
* *stderr*
* *trenorder*
* *tvalues*
* *y*
* *ys\_lagged*
|
#### Methods
| | |
| --- | --- |
| [`acf`](statsmodels.tsa.vector_ar.var_model.varresults.acf#statsmodels.tsa.vector_ar.var_model.VARResults.acf "statsmodels.tsa.vector_ar.var_model.VARResults.acf")([nlags]) | Compute theoretical autocovariance function |
| [`acorr`](statsmodels.tsa.vector_ar.var_model.varresults.acorr#statsmodels.tsa.vector_ar.var_model.VARResults.acorr "statsmodels.tsa.vector_ar.var_model.VARResults.acorr")([nlags]) | Compute theoretical autocorrelation function |
| [`bse`](statsmodels.tsa.vector_ar.var_model.varresults.bse#statsmodels.tsa.vector_ar.var_model.VARResults.bse "statsmodels.tsa.vector_ar.var_model.VARResults.bse")() | Standard errors of coefficients, reshaped to match in size |
| [`cov_params`](statsmodels.tsa.vector_ar.var_model.varresults.cov_params#statsmodels.tsa.vector_ar.var_model.VARResults.cov_params "statsmodels.tsa.vector_ar.var_model.VARResults.cov_params")() | Estimated variance-covariance of model coefficients |
| [`cov_ybar`](statsmodels.tsa.vector_ar.var_model.varresults.cov_ybar#statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar "statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar")() | Asymptotically consistent estimate of covariance of the sample mean |
| [`detomega`](statsmodels.tsa.vector_ar.var_model.varresults.detomega#statsmodels.tsa.vector_ar.var_model.VARResults.detomega "statsmodels.tsa.vector_ar.var_model.VARResults.detomega")() | Return determinant of white noise covariance with degrees of freedom correction: |
| [`fevd`](statsmodels.tsa.vector_ar.var_model.varresults.fevd#statsmodels.tsa.vector_ar.var_model.VARResults.fevd "statsmodels.tsa.vector_ar.var_model.VARResults.fevd")([periods, var\_decomp]) | Compute forecast error variance decomposition (βfevdβ) |
| [`fittedvalues`](statsmodels.tsa.vector_ar.var_model.varresults.fittedvalues#statsmodels.tsa.vector_ar.var_model.VARResults.fittedvalues "statsmodels.tsa.vector_ar.var_model.VARResults.fittedvalues")() | The predicted insample values of the response variables of the model. |
| [`forecast`](statsmodels.tsa.vector_ar.var_model.varresults.forecast#statsmodels.tsa.vector_ar.var_model.VARResults.forecast "statsmodels.tsa.vector_ar.var_model.VARResults.forecast")(y, steps[, exog\_future]) | Produce linear minimum MSE forecasts for desired number of steps ahead, using prior values y |
| [`forecast_cov`](statsmodels.tsa.vector_ar.var_model.varresults.forecast_cov#statsmodels.tsa.vector_ar.var_model.VARResults.forecast_cov "statsmodels.tsa.vector_ar.var_model.VARResults.forecast_cov")([steps, method]) | Compute forecast covariance matrices for desired number of steps |
| [`forecast_interval`](statsmodels.tsa.vector_ar.var_model.varresults.forecast_interval#statsmodels.tsa.vector_ar.var_model.VARResults.forecast_interval "statsmodels.tsa.vector_ar.var_model.VARResults.forecast_interval")(y, steps[, alpha, exog\_future]) | Construct forecast interval estimates assuming the y are Gaussian |
| [`get_eq_index`](statsmodels.tsa.vector_ar.var_model.varresults.get_eq_index#statsmodels.tsa.vector_ar.var_model.VARResults.get_eq_index "statsmodels.tsa.vector_ar.var_model.VARResults.get_eq_index")(name) | Return integer position of requested equation name |
| [`info_criteria`](statsmodels.tsa.vector_ar.var_model.varresults.info_criteria#statsmodels.tsa.vector_ar.var_model.VARResults.info_criteria "statsmodels.tsa.vector_ar.var_model.VARResults.info_criteria")() | information criteria for lagorder selection |
| [`intercept_longrun`](statsmodels.tsa.vector_ar.var_model.varresults.intercept_longrun#statsmodels.tsa.vector_ar.var_model.VARResults.intercept_longrun "statsmodels.tsa.vector_ar.var_model.VARResults.intercept_longrun")() | Long run intercept of stable VAR process |
| [`irf`](statsmodels.tsa.vector_ar.var_model.varresults.irf#statsmodels.tsa.vector_ar.var_model.VARResults.irf "statsmodels.tsa.vector_ar.var_model.VARResults.irf")([periods, var\_decomp, var\_order]) | Analyze impulse responses to shocks in system |
| [`irf_errband_mc`](statsmodels.tsa.vector_ar.var_model.varresults.irf_errband_mc#statsmodels.tsa.vector_ar.var_model.VARResults.irf_errband_mc "statsmodels.tsa.vector_ar.var_model.VARResults.irf_errband_mc")([orth, repl, T, signif, β¦]) | Compute Monte Carlo integrated error bands assuming normally distributed for impulse response functions |
| [`irf_resim`](statsmodels.tsa.vector_ar.var_model.varresults.irf_resim#statsmodels.tsa.vector_ar.var_model.VARResults.irf_resim "statsmodels.tsa.vector_ar.var_model.VARResults.irf_resim")([orth, repl, T, seed, burn, cum]) | Simulates impulse response function, returning an array of simulations. |
| [`is_stable`](statsmodels.tsa.vector_ar.var_model.varresults.is_stable#statsmodels.tsa.vector_ar.var_model.VARResults.is_stable "statsmodels.tsa.vector_ar.var_model.VARResults.is_stable")([verbose]) | Determine stability based on model coefficients |
| [`llf`](statsmodels.tsa.vector_ar.var_model.varresults.llf#statsmodels.tsa.vector_ar.var_model.VARResults.llf "statsmodels.tsa.vector_ar.var_model.VARResults.llf")() | Compute VAR(p) loglikelihood |
| [`long_run_effects`](statsmodels.tsa.vector_ar.var_model.varresults.long_run_effects#statsmodels.tsa.vector_ar.var_model.VARResults.long_run_effects "statsmodels.tsa.vector_ar.var_model.VARResults.long_run_effects")() | Compute long-run effect of unit impulse |
| [`ma_rep`](statsmodels.tsa.vector_ar.var_model.varresults.ma_rep#statsmodels.tsa.vector_ar.var_model.VARResults.ma_rep "statsmodels.tsa.vector_ar.var_model.VARResults.ma_rep")([maxn]) | Compute MA(\(\infty\)) coefficient matrices |
| [`mean`](statsmodels.tsa.vector_ar.var_model.varresults.mean#statsmodels.tsa.vector_ar.var_model.VARResults.mean "statsmodels.tsa.vector_ar.var_model.VARResults.mean")() | Long run intercept of stable VAR process |
| [`mse`](statsmodels.tsa.vector_ar.var_model.varresults.mse#statsmodels.tsa.vector_ar.var_model.VARResults.mse "statsmodels.tsa.vector_ar.var_model.VARResults.mse")(steps) | Compute theoretical forecast error variance matrices |
| [`orth_ma_rep`](statsmodels.tsa.vector_ar.var_model.varresults.orth_ma_rep#statsmodels.tsa.vector_ar.var_model.VARResults.orth_ma_rep "statsmodels.tsa.vector_ar.var_model.VARResults.orth_ma_rep")([maxn, P]) | Compute orthogonalized MA coefficient matrices using P matrix such that \(\Sigma\_u = PP^\prime\). |
| [`plot`](statsmodels.tsa.vector_ar.var_model.varresults.plot#statsmodels.tsa.vector_ar.var_model.VARResults.plot "statsmodels.tsa.vector_ar.var_model.VARResults.plot")() | Plot input time series |
| [`plot_acorr`](statsmodels.tsa.vector_ar.var_model.varresults.plot_acorr#statsmodels.tsa.vector_ar.var_model.VARResults.plot_acorr "statsmodels.tsa.vector_ar.var_model.VARResults.plot_acorr")([nlags, resid, linewidth]) | Plot autocorrelation of sample (endog) or residuals |
| [`plot_forecast`](statsmodels.tsa.vector_ar.var_model.varresults.plot_forecast#statsmodels.tsa.vector_ar.var_model.VARResults.plot_forecast "statsmodels.tsa.vector_ar.var_model.VARResults.plot_forecast")(steps[, alpha, plot\_stderr]) | Plot forecast |
| [`plot_sample_acorr`](statsmodels.tsa.vector_ar.var_model.varresults.plot_sample_acorr#statsmodels.tsa.vector_ar.var_model.VARResults.plot_sample_acorr "statsmodels.tsa.vector_ar.var_model.VARResults.plot_sample_acorr")([nlags, linewidth]) | Plot theoretical autocorrelation function |
| [`plotsim`](statsmodels.tsa.vector_ar.var_model.varresults.plotsim#statsmodels.tsa.vector_ar.var_model.VARResults.plotsim "statsmodels.tsa.vector_ar.var_model.VARResults.plotsim")([steps, offset, seed]) | Plot a simulation from the VAR(p) process for the desired number of steps |
| [`pvalues`](statsmodels.tsa.vector_ar.var_model.varresults.pvalues#statsmodels.tsa.vector_ar.var_model.VARResults.pvalues "statsmodels.tsa.vector_ar.var_model.VARResults.pvalues")() | Two-sided p-values for model coefficients from Student t-distribution |
| [`pvalues_dt`](statsmodels.tsa.vector_ar.var_model.varresults.pvalues_dt#statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt "statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt")() | |
| [`pvalues_endog_lagged`](statsmodels.tsa.vector_ar.var_model.varresults.pvalues_endog_lagged#statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_endog_lagged "statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_endog_lagged")() | |
| [`reorder`](statsmodels.tsa.vector_ar.var_model.varresults.reorder#statsmodels.tsa.vector_ar.var_model.VARResults.reorder "statsmodels.tsa.vector_ar.var_model.VARResults.reorder")(order) | Reorder variables for structural specification |
| [`resid`](statsmodels.tsa.vector_ar.var_model.varresults.resid#statsmodels.tsa.vector_ar.var_model.VARResults.resid "statsmodels.tsa.vector_ar.var_model.VARResults.resid")() | Residuals of response variable resulting from estimated coefficients |
| [`resid_acorr`](statsmodels.tsa.vector_ar.var_model.varresults.resid_acorr#statsmodels.tsa.vector_ar.var_model.VARResults.resid_acorr "statsmodels.tsa.vector_ar.var_model.VARResults.resid_acorr")([nlags]) | Compute sample autocorrelation (including lag 0) |
| [`resid_acov`](statsmodels.tsa.vector_ar.var_model.varresults.resid_acov#statsmodels.tsa.vector_ar.var_model.VARResults.resid_acov "statsmodels.tsa.vector_ar.var_model.VARResults.resid_acov")([nlags]) | Compute centered sample autocovariance (including lag 0) |
| [`resid_corr`](statsmodels.tsa.vector_ar.var_model.varresults.resid_corr#statsmodels.tsa.vector_ar.var_model.VARResults.resid_corr "statsmodels.tsa.vector_ar.var_model.VARResults.resid_corr")() | Centered residual correlation matrix |
| [`roots`](statsmodels.tsa.vector_ar.var_model.varresults.roots#statsmodels.tsa.vector_ar.var_model.VARResults.roots "statsmodels.tsa.vector_ar.var_model.VARResults.roots")() | |
| [`sample_acorr`](statsmodels.tsa.vector_ar.var_model.varresults.sample_acorr#statsmodels.tsa.vector_ar.var_model.VARResults.sample_acorr "statsmodels.tsa.vector_ar.var_model.VARResults.sample_acorr")([nlags]) | |
| [`sample_acov`](statsmodels.tsa.vector_ar.var_model.varresults.sample_acov#statsmodels.tsa.vector_ar.var_model.VARResults.sample_acov "statsmodels.tsa.vector_ar.var_model.VARResults.sample_acov")([nlags]) | |
| [`sigma_u_mle`](statsmodels.tsa.vector_ar.var_model.varresults.sigma_u_mle#statsmodels.tsa.vector_ar.var_model.VARResults.sigma_u_mle "statsmodels.tsa.vector_ar.var_model.VARResults.sigma_u_mle")() | (Biased) maximum likelihood estimate of noise process covariance |
| [`simulate_var`](statsmodels.tsa.vector_ar.var_model.varresults.simulate_var#statsmodels.tsa.vector_ar.var_model.VARResults.simulate_var "statsmodels.tsa.vector_ar.var_model.VARResults.simulate_var")([steps, offset, seed]) | simulate the VAR(p) process for the desired number of steps |
| [`stderr`](statsmodels.tsa.vector_ar.var_model.varresults.stderr#statsmodels.tsa.vector_ar.var_model.VARResults.stderr "statsmodels.tsa.vector_ar.var_model.VARResults.stderr")() | Standard errors of coefficients, reshaped to match in size |
| [`stderr_dt`](statsmodels.tsa.vector_ar.var_model.varresults.stderr_dt#statsmodels.tsa.vector_ar.var_model.VARResults.stderr_dt "statsmodels.tsa.vector_ar.var_model.VARResults.stderr_dt")() | |
| [`stderr_endog_lagged`](statsmodels.tsa.vector_ar.var_model.varresults.stderr_endog_lagged#statsmodels.tsa.vector_ar.var_model.VARResults.stderr_endog_lagged "statsmodels.tsa.vector_ar.var_model.VARResults.stderr_endog_lagged")() | |
| [`summary`](statsmodels.tsa.vector_ar.var_model.varresults.summary#statsmodels.tsa.vector_ar.var_model.VARResults.summary "statsmodels.tsa.vector_ar.var_model.VARResults.summary")() | Compute console output summary of estimates |
| [`test_causality`](statsmodels.tsa.vector_ar.var_model.varresults.test_causality#statsmodels.tsa.vector_ar.var_model.VARResults.test_causality "statsmodels.tsa.vector_ar.var_model.VARResults.test_causality")(caused[, causing, kind, signif]) | Test Granger causality |
| [`test_inst_causality`](statsmodels.tsa.vector_ar.var_model.varresults.test_inst_causality#statsmodels.tsa.vector_ar.var_model.VARResults.test_inst_causality "statsmodels.tsa.vector_ar.var_model.VARResults.test_inst_causality")(causing[, signif]) | Test for instantaneous causality |
| [`test_normality`](statsmodels.tsa.vector_ar.var_model.varresults.test_normality#statsmodels.tsa.vector_ar.var_model.VARResults.test_normality "statsmodels.tsa.vector_ar.var_model.VARResults.test_normality")([signif]) | Test assumption of normal-distributed errors using Jarque-Bera-style omnibus Chi^2 test. |
| [`test_whiteness`](statsmodels.tsa.vector_ar.var_model.varresults.test_whiteness#statsmodels.tsa.vector_ar.var_model.VARResults.test_whiteness "statsmodels.tsa.vector_ar.var_model.VARResults.test_whiteness")([nlags, signif, adjusted]) | Residual whiteness tests using Portmanteau test |
| [`to_vecm`](statsmodels.tsa.vector_ar.var_model.varresults.to_vecm#statsmodels.tsa.vector_ar.var_model.VARResults.to_vecm "statsmodels.tsa.vector_ar.var_model.VARResults.to_vecm")() | |
| [`tvalues`](statsmodels.tsa.vector_ar.var_model.varresults.tvalues#statsmodels.tsa.vector_ar.var_model.VARResults.tvalues "statsmodels.tsa.vector_ar.var_model.VARResults.tvalues")() | Compute t-statistics. |
| [`tvalues_dt`](statsmodels.tsa.vector_ar.var_model.varresults.tvalues_dt#statsmodels.tsa.vector_ar.var_model.VARResults.tvalues_dt "statsmodels.tsa.vector_ar.var_model.VARResults.tvalues_dt")() | |
| [`tvalues_endog_lagged`](statsmodels.tsa.vector_ar.var_model.varresults.tvalues_endog_lagged#statsmodels.tsa.vector_ar.var_model.VARResults.tvalues_endog_lagged "statsmodels.tsa.vector_ar.var_model.VARResults.tvalues_endog_lagged")() | |
#### Attributes
| | |
| --- | --- |
| `aic` | Akaike information criterion |
| `bic` | Bayesian a.k.a. |
| `df_model` | Number of estimated parameters, including the intercept / trends |
| `df_resid` | Number of observations minus number of estimated parameters |
| `fpe` | Final Prediction Error (FPE) |
| `hqic` | Hannan-Quinn criterion |
| programming_docs |
statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_gamma statsmodels.tsa.vector\_ar.vecm.VECMResults.stderr\_gamma
=========================================================
`VECMResults.stderr_gamma()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.stderr_gamma)
statsmodels statsmodels.stats.weightstats.CompareMeans.zconfint_diff statsmodels.stats.weightstats.CompareMeans.zconfint\_diff
=========================================================
`CompareMeans.zconfint_diff(alpha=0.05, alternative='two-sided', usevar='pooled')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.zconfint_diff)
confidence interval for the difference in means
| Parameters: | * **alpha** (*float*) β significance level for the confidence interval, coverage is `1-alpha`
* **alternative** (*string*) β This specifies the alternative hypothesis for the test that corresponds to the confidence interval. The alternative hypothesis, H1, has to be one of the following : βtwo-sidedβ: H1: difference in means not equal to value (default) βlargerβ : H1: difference in means larger than value βsmallerβ : H1: difference in means smaller than value
* **usevar** (*string**,* *'pooled'* *or* *'unequal'*) β If `pooled`, then the standard deviation of the samples is assumed to be the same. If `unequal`, then Welsh ttest with Satterthwait degrees of freedom is used
|
| Returns: | **lower, upper** β lower and upper limits of the confidence interval |
| Return type: | floats |
#### Notes
The result is independent of the user specified ddof.
statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_det_coef statsmodels.tsa.vector\_ar.vecm.VECMResults.tvalues\_det\_coef
==============================================================
`VECMResults.tvalues_det_coef()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.tvalues_det_coef)
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_anscombe statsmodels.genmod.generalized\_estimating\_equations.GEEResults.resid\_anscombe
================================================================================
`GEEResults.resid_anscombe()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid_anscombe)
statsmodels statsmodels.tsa.arima_model.ARMAResults.save statsmodels.tsa.arima\_model.ARMAResults.save
=============================================
`ARMAResults.save(fname, remove_data=False)`
save a pickle of this instance
| Parameters: | * **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle.
* **remove\_data** (*bool*) β If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None.
|
#### Notes
If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception.
statsmodels statsmodels.regression.linear_model.RegressionResults.mse_total statsmodels.regression.linear\_model.RegressionResults.mse\_total
=================================================================
`RegressionResults.mse_total()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.mse_total)
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.cov_params statsmodels.tsa.vector\_ar.var\_model.VARResults.cov\_params
============================================================
`VARResults.cov_params()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.cov_params)
Estimated variance-covariance of model coefficients
#### Notes
Covariance of vec(B), where B is the matrix [params\_for\_deterministic\_terms, A\_1, β¦, A\_p] with the shape (K x (Kp + number\_of\_deterministic\_terms)) Adjusted to be an unbiased estimator Ref: LΓΌtkepohl p.74-75
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.hqic statsmodels.tsa.statespace.structural.UnobservedComponentsResults.hqic
======================================================================
`UnobservedComponentsResults.hqic()`
(float) Hannan-Quinn Information Criterion
statsmodels statsmodels.genmod.families.family.Tweedie.loglike_obs statsmodels.genmod.families.family.Tweedie.loglike\_obs
=======================================================
`Tweedie.loglike_obs(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Tweedie.loglike_obs)
The log-likelihood function for each observation in terms of the fitted mean response for the Tweedie distribution.
| Parameters: | * **endog** (*array*) β Usually the endogenous response variable.
* **mu** (*array*) β Usually but not always the fitted mean response variable.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **scale** (*float*) β The scale parameter. The default is 1.
|
| Returns: | **ll\_i** β The value of the loglikelihood evaluated at (endog, mu, var\_weights, scale) as defined below. |
| Return type: | float |
#### Notes
This is not implemented because of the complexity of calculating an infinite series of sums.
statsmodels statsmodels.multivariate.multivariate_ols._MultivariateOLS statsmodels.multivariate.multivariate\_ols.\_MultivariateOLS
============================================================
`class statsmodels.multivariate.multivariate_ols._MultivariateOLS(endog, exog, missing='none', hasconst=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/multivariate_ols.html#_MultivariateOLS)
Multivariate linear model via least squares
| Parameters: | * **endog** (*array\_like*) β Dependent variables. A nobs x k\_endog array where nobs is the number of observations and k\_endog is the number of dependent variables
* **exog** (*array\_like*) β Independent variables. A nobs x k\_exog array where nobs is the number of observations and k\_exog is the number of independent variables. An intercept is not included by default and should be added by the user (models specified using a formula include an intercept by default)
|
`endog`
*array* β See Parameters.
`exog`
*array* β See Parameters.
#### Methods
| | |
| --- | --- |
| [`fit`](statsmodels.multivariate.multivariate_ols._multivariateols.fit#statsmodels.multivariate.multivariate_ols._MultivariateOLS.fit "statsmodels.multivariate.multivariate_ols._MultivariateOLS.fit")([method]) | Fit a model to data. |
| [`from_formula`](statsmodels.multivariate.multivariate_ols._multivariateols.from_formula#statsmodels.multivariate.multivariate_ols._MultivariateOLS.from_formula "statsmodels.multivariate.multivariate_ols._MultivariateOLS.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. |
| [`predict`](statsmodels.multivariate.multivariate_ols._multivariateols.predict#statsmodels.multivariate.multivariate_ols._MultivariateOLS.predict "statsmodels.multivariate.multivariate_ols._MultivariateOLS.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. |
#### Attributes
| | |
| --- | --- |
| `endog_names` | Names of endogenous variables |
| `exog_names` | Names of exogenous variables |
statsmodels statsmodels.sandbox.regression.gmm.IVGMM.momcond_mean statsmodels.sandbox.regression.gmm.IVGMM.momcond\_mean
======================================================
`IVGMM.momcond_mean(params)`
mean of moment conditions,
statsmodels statsmodels.stats.contingency_tables.Table.marginal_probabilities statsmodels.stats.contingency\_tables.Table.marginal\_probabilities
===================================================================
`Table.marginal_probabilities()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.marginal_probabilities)
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.tvalues statsmodels.genmod.generalized\_estimating\_equations.GEEResults.tvalues
========================================================================
`GEEResults.tvalues()`
Return the t-statistic for a given parameter estimate.
statsmodels statsmodels.genmod.families.family.Poisson.resid_dev statsmodels.genmod.families.family.Poisson.resid\_dev
=====================================================
`Poisson.resid_dev(endog, mu, var_weights=1.0, scale=1.0)`
The deviance residuals
| Parameters: | * **endog** (*array-like*) β The endogenous response variable
* **mu** (*array-like*) β The inverse of the link function at the linear predicted values.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **scale** (*float**,* *optional*) β An optional scale argument. The default is 1.
|
| Returns: | **resid\_dev** β Deviance residuals as defined below. |
| Return type: | float |
#### Notes
The deviance residuals are defined by the contribution D\_i of observation i to the deviance as
\[resid\\_dev\_i = sign(y\_i-\mu\_i) \sqrt{D\_i}\] D\_i is calculated from the \_resid\_dev method in each family. Distribution-specific documentation of the calculation is available there.
statsmodels statsmodels.duration.hazard_regression.PHReg.initialize statsmodels.duration.hazard\_regression.PHReg.initialize
========================================================
`PHReg.initialize()`
Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed.
statsmodels statsmodels.robust.robust_linear_model.RLMResults.bcov_scaled statsmodels.robust.robust\_linear\_model.RLMResults.bcov\_scaled
================================================================
`RLMResults.bcov_scaled()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLMResults.bcov_scaled)
statsmodels statsmodels.discrete.discrete_model.DiscreteResults.llf statsmodels.discrete.discrete\_model.DiscreteResults.llf
========================================================
`DiscreteResults.llf()`
statsmodels statsmodels.stats.contingency_tables.Table2x2.summary statsmodels.stats.contingency\_tables.Table2x2.summary
======================================================
`Table2x2.summary(alpha=0.05, float_format='%.3f', method='normal')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.summary)
Summarizes results for a 2x2 table analysis.
| Parameters: | * **alpha** (*float*) β `1 - alpha` is the nominal coverage probability of the confidence intervals.
* **float\_format** (*string*) β Used to format the numeric values in the table.
* **method** (*string*) β The method for producing the confidence interval. Currently must be βnormalβ which uses the normal approximation.
|
statsmodels statsmodels.sandbox.distributions.transformed.SquareFunc.inverseminus statsmodels.sandbox.distributions.transformed.SquareFunc.inverseminus
=====================================================================
`SquareFunc.inverseminus(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/transformed.html#SquareFunc.inverseminus)
statsmodels statsmodels.discrete.discrete_model.LogitResults.set_null_options statsmodels.discrete.discrete\_model.LogitResults.set\_null\_options
====================================================================
`LogitResults.set_null_options(llnull=None, attach_results=True, **kwds)`
set fit options for Null (constant-only) model
This resets the cache for related attributes which is potentially fragile. This only sets the option, the null model is estimated when llnull is accessed, if llnull is not yet in cache.
| Parameters: | * **llnull** (*None* *or* *float*) β If llnull is not None, then the value will be directly assigned to the cached attribute βllnullβ.
* **attach\_results** (*bool*) β Sets an internal flag whether the results instance of the null model should be attached. By default without calling this method, thenull model results are not attached and only the loglikelihood value llnull is stored.
* **kwds** (*keyword arguments*) β `kwds` are directly used as fit keyword arguments for the null model, overriding any provided defaults.
|
| Returns: | |
| Return type: | no returns, modifies attributes of this instance |
statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.cov_params statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.cov\_params
==========================================================================
`GeneralizedPoissonResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)`
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar.
| Parameters: | * **r\_matrix** (*array-like*) β Can be 1d, or 2d. Can be used alone or with other.
* **column** (*array-like**,* *optional*) β Must be used on its own. Can be 0d or 1d see below.
* **scale** (*float**,* *optional*) β Can be specified or not. Default is None, which means that the scale argument is taken from the model.
* **other** (*array-like**,* *optional*) β Can be used when r\_matrix is specified.
|
| Returns: | **cov** β covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. |
| Return type: | ndarray |
#### Notes
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)`
If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T`
If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T`
If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d
OR
`(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.zvalues statsmodels.tsa.statespace.sarimax.SARIMAXResults.zvalues
=========================================================
`SARIMAXResults.zvalues()`
(array) The z-statistics for the coefficients.
statsmodels statsmodels.genmod.cov_struct.Exchangeable.initialize statsmodels.genmod.cov\_struct.Exchangeable.initialize
======================================================
`Exchangeable.initialize(model)`
Called by GEE, used by implementations that need additional setup prior to running `fit`.
| Parameters: | **model** (*GEE class*) β A reference to the parent GEE class instance. |
statsmodels statsmodels.genmod.families.family.Family.fitted statsmodels.genmod.families.family.Family.fitted
================================================
`Family.fitted(lin_pred)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Family.fitted)
Fitted values based on linear predictors lin\_pred.
| Parameters: | **lin\_pred** (*array*) β Values of the linear predictor of the model. \(X \cdot \beta\) in a classical linear model. |
| Returns: | **mu** β The mean response variables given by the inverse of the link function. |
| Return type: | array |
statsmodels statsmodels.miscmodels.tmodel.TLinearModel.fit statsmodels.miscmodels.tmodel.TLinearModel.fit
==============================================
`TLinearModel.fit(start_params=None, method='nm', maxiter=500, full_output=1, disp=1, callback=None, retall=0, **kwargs)`
Fit the model using maximum likelihood.
The rest of the docstring is from statsmodels.LikelihoodModel.fit
statsmodels statsmodels.tsa.ar_model.ARResults.summary statsmodels.tsa.ar\_model.ARResults.summary
===========================================
`ARResults.summary()`
statsmodels statsmodels.sandbox.tsa.movstat.movmoment statsmodels.sandbox.tsa.movstat.movmoment
=========================================
`statsmodels.sandbox.tsa.movstat.movmoment(x, k, windowsize=3, lag='lagged')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/movstat.html#movmoment)
non-central moment
| Parameters: | * **x** (*array*) β time series data
* **windsize** (*int*) β window size
* **lag** (*'lagged'**,* *'centered'**, or* *'leading'*) β location of window relative to current position
|
| Returns: | **mk** β k-th moving non-central moment, with same shape as x |
| Return type: | array |
#### Notes
If data x is 2d, then moving moment is calculated for each column.
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.score statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.score
======================================================================
`ZeroInflatedGeneralizedPoisson.score(params)`
Score vector of model.
The gradient of logL with respect to each parameter.
statsmodels statsmodels.stats.weightstats._tconfint_generic statsmodels.stats.weightstats.\_tconfint\_generic
=================================================
`statsmodels.stats.weightstats._tconfint_generic(mean, std_mean, dof, alpha, alternative)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#_tconfint_generic)
generic t-confint to save typing
statsmodels statsmodels.stats.outliers_influence.OLSInfluence.dffits statsmodels.stats.outliers\_influence.OLSInfluence.dffits
=========================================================
`OLSInfluence.dffits()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.dffits)
(cached attribute) dffits measure for influence of an observation
based on resid\_studentized\_external, uses results from leave-one-observation-out loop
It is recommended that observations with dffits large than a threshold of 2 sqrt{k / n} where k is the number of parameters, should be investigated.
| Returns: | * **dffits** (*float*)
* **dffits\_threshold** (*float*)
|
#### References
[Wikipedia](http://en.wikipedia.org/wiki/DFFITS)
statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.predict statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.predict
======================================================================
`GeneralizedPoissonResults.predict(exog=None, transform=True, *args, **kwargs)`
Call self.model.predict with self.params as the first argument.
| Parameters: | * **exog** (*array-like**,* *optional*) β The values for which you want to predict. see Notes below.
* **transform** (*bool**,* *optional*) β If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, youβd need to log the data first.
* **kwargs** (*args**,*) β Some models can take additional arguments or keywords, see the predict method of the model for the details.
|
| Returns: | **prediction** β See self.model.predict |
| Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") |
#### Notes
The types of exog that are supported depends on whether a formula was used in the specification of the model.
If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object.
If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array.
Row indices as in pandas data frames are supported, and added to the returned prediction.
| programming_docs |
statsmodels statsmodels.graphics.gofplots.ProbPlot statsmodels.graphics.gofplots.ProbPlot
======================================
`class statsmodels.graphics.gofplots.ProbPlot(data, dist=<scipy.stats._continuous_distns.norm_gen object>, fit=False, distargs=(), a=0, loc=0, scale=1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#ProbPlot)
Class for convenient construction of Q-Q, P-P, and probability plots.
Can take arguments specifying the parameters for dist or fit them automatically. (See fit under kwargs.)
| Parameters: | * **data** (*array-like*) β 1d data array
* **dist** (*A scipy.stats* *or* *statsmodels distribution*) β Compare x against dist. The default is scipy.stats.distributions.norm (a standard normal).
* **distargs** (*tuple*) β A tuple of arguments passed to dist to specify it fully so dist.ppf may be called.
* **loc** (*float*) β Location parameter for dist
* **a** (*float*) β Offset for the plotting position of an expected order statistic, for example. The plotting positions are given by (i - a)/(nobs - 2\*a + 1) for i in range(0,nobs+1)
* **scale** (*float*) β Scale parameter for dist
* **fit** (*boolean*) β If fit is false, loc, scale, and distargs are passed to the distribution. If fit is True then the parameters for dist are fit automatically using dist.fit. The quantiles are formed from the standardized data, after subtracting the fitted loc and dividing by the fitted scale.
|
See also
`scipy.stats.probplot`
#### Notes
1. Depends on matplotlib.
2. `If fit is True then the parameters are fit using the` distributionβs `fit()` method.
3. `The call signatures for the qqplot, ppplot, and probplot` methods are similar, so examples 1 through 4 apply to all three methods.
4. The three plotting methods are summarized below:
`ppplot : Probability-Probability plot` Compares the sample and theoretical probabilities (percentiles).
`qqplot : Quantile-Quantile plot` Compares the sample and theoretical quantiles
`probplot : Probability plot` Same as a Q-Q plot, however probabilities are shown in the scale of the theoretical distribution (x-axis) and the y-axis contains unscaled quantiles of the sample data.
#### Examples
```
>>> import statsmodels.api as sm
>>> from matplotlib import pyplot as plt
```
```
>>> # example 1
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> model = sm.OLS(data.endog, data.exog)
>>> mod_fit = model.fit()
>>> res = mod_fit.resid # residuals
>>> probplot = sm.ProbPlot(res)
>>> probplot.qqplot()
>>> plt.show()
```
qqplot of the residuals against quantiles of t-distribution with 4 degrees of freedom:
```
>>> # example 2
>>> import scipy.stats as stats
>>> probplot = sm.ProbPlot(res, stats.t, distargs=(4,))
>>> fig = probplot.qqplot()
>>> plt.show()
```
qqplot against same as above, but with mean 3 and std 10:
```
>>> # example 3
>>> probplot = sm.ProbPlot(res, stats.t, distargs=(4,), loc=3, scale=10)
>>> fig = probplot.qqplot()
>>> plt.show()
```
Automatically determine parameters for t distribution including the loc and scale:
```
>>> # example 4
>>> probplot = sm.ProbPlot(res, stats.t, fit=True)
>>> fig = probplot.qqplot(line='45')
>>> plt.show()
```
A second `ProbPlot` object can be used to compare two seperate sample sets by using the `other` kwarg in the `qqplot` and `ppplot` methods.
```
>>> # example 5
>>> import numpy as np
>>> x = np.random.normal(loc=8.25, scale=2.75, size=37)
>>> y = np.random.normal(loc=8.75, scale=3.25, size=37)
>>> pp_x = sm.ProbPlot(x, fit=True)
>>> pp_y = sm.ProbPlot(y, fit=True)
>>> fig = pp_x.qqplot(line='45', other=pp_y)
>>> plt.show()
```
The following plot displays some options, follow the link to see the code.
([Source code](../plots/graphics_gofplots_qqplot.py))
([png](../plots/graphics_gofplots_qqplot_00.png), [hires.png](../plots/graphics_gofplots_qqplot_00.hires.png), [pdf](../plots/graphics_gofplots_qqplot_00.pdf))
([png](../plots/graphics_gofplots_qqplot_01.png), [hires.png](../plots/graphics_gofplots_qqplot_01.hires.png), [pdf](../plots/graphics_gofplots_qqplot_01.pdf))
([png](../plots/graphics_gofplots_qqplot_02.png), [hires.png](../plots/graphics_gofplots_qqplot_02.hires.png), [pdf](../plots/graphics_gofplots_qqplot_02.pdf))
([png](../plots/graphics_gofplots_qqplot_03.png), [hires.png](../plots/graphics_gofplots_qqplot_03.hires.png), [pdf](../plots/graphics_gofplots_qqplot_03.pdf))
#### Methods
| | |
| --- | --- |
| [`ppplot`](statsmodels.graphics.gofplots.probplot.ppplot#statsmodels.graphics.gofplots.ProbPlot.ppplot "statsmodels.graphics.gofplots.ProbPlot.ppplot")([xlabel, ylabel, line, other, ax]) | P-P plot of the percentiles (probabilities) of x versus the probabilities (percetiles) of a distribution. |
| [`probplot`](statsmodels.graphics.gofplots.probplot.probplot#statsmodels.graphics.gofplots.ProbPlot.probplot "statsmodels.graphics.gofplots.ProbPlot.probplot")([xlabel, ylabel, line, exceed, ax]) | Probability plot of the unscaled quantiles of x versus the probabilities of a distibution (not to be confused with a P-P plot). |
| [`qqplot`](statsmodels.graphics.gofplots.probplot.qqplot#statsmodels.graphics.gofplots.ProbPlot.qqplot "statsmodels.graphics.gofplots.ProbPlot.qqplot")([xlabel, ylabel, line, other, ax]) | Q-Q plot of the quantiles of x versus the quantiles/ppf of a distribution or the quantiles of another `ProbPlot` instance. |
| [`sample_percentiles`](statsmodels.graphics.gofplots.probplot.sample_percentiles#statsmodels.graphics.gofplots.ProbPlot.sample_percentiles "statsmodels.graphics.gofplots.ProbPlot.sample_percentiles")() | |
| [`sample_quantiles`](statsmodels.graphics.gofplots.probplot.sample_quantiles#statsmodels.graphics.gofplots.ProbPlot.sample_quantiles "statsmodels.graphics.gofplots.ProbPlot.sample_quantiles")() | |
| [`sorted_data`](statsmodels.graphics.gofplots.probplot.sorted_data#statsmodels.graphics.gofplots.ProbPlot.sorted_data "statsmodels.graphics.gofplots.ProbPlot.sorted_data")() | |
| [`theoretical_percentiles`](statsmodels.graphics.gofplots.probplot.theoretical_percentiles#statsmodels.graphics.gofplots.ProbPlot.theoretical_percentiles "statsmodels.graphics.gofplots.ProbPlot.theoretical_percentiles")() | |
| [`theoretical_quantiles`](statsmodels.graphics.gofplots.probplot.theoretical_quantiles#statsmodels.graphics.gofplots.ProbPlot.theoretical_quantiles "statsmodels.graphics.gofplots.ProbPlot.theoretical_quantiles")() | |
statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.set_filter_method statsmodels.tsa.statespace.mlemodel.MLEModel.set\_filter\_method
================================================================
`MLEModel.set_filter_method(filter_method=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.set_filter_method)
Set the filtering method
The filtering method controls aspects of which Kalman filtering approach will be used.
| Parameters: | * **filter\_method** (*integer**,* *optional*) β Bitmask value to set the filter method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details.
|
#### Notes
This method is rarely used. See the corresponding function in the `KalmanFilter` class for details.
statsmodels statsmodels.miscmodels.count.PoissonGMLE.score_obs statsmodels.miscmodels.count.PoissonGMLE.score\_obs
===================================================
`PoissonGMLE.score_obs(params, **kwds)`
Jacobian/Gradient of log-likelihood evaluated at params for each observation.
statsmodels statsmodels.stats.sandwich_covariance.cov_hc1 statsmodels.stats.sandwich\_covariance.cov\_hc1
===============================================
`statsmodels.stats.sandwich_covariance.cov_hc1(results)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/sandwich_covariance.html#cov_hc1)
See statsmodels.RegressionResults
statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.logposterior_grad statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.logposterior\_grad
=============================================================================
`BinomialBayesMixedGLM.logposterior_grad(params)`
The gradient of the log posterior.
statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.normalized_cov_params statsmodels.sandbox.regression.gmm.IVRegressionResults.normalized\_cov\_params
==============================================================================
`IVRegressionResults.normalized_cov_params()`
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.loglikelihood_burn statsmodels.tsa.statespace.mlemodel.MLEResults.loglikelihood\_burn
==================================================================
`MLEResults.loglikelihood_burn()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.loglikelihood_burn)
(float) The number of observations during which the likelihood is not evaluated.
statsmodels statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu statsmodels.sandbox.regression.gmm.GMM.gmmobjective\_cu
=======================================================
`GMM.gmmobjective_cu(params, weights_method='cov', wargs=())` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.gmmobjective_cu)
objective function for continuously updating GMM minimization
| Parameters: | **params** (*array*) β parameter values at which objective is evaluated |
| Returns: | **jval** β value of objective function |
| Return type: | float |
statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults statsmodels.sandbox.regression.gmm.IVGMMResults
===============================================
`class statsmodels.sandbox.regression.gmm.IVGMMResults(*args, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVGMMResults)
#### Methods
| | |
| --- | --- |
| [`bse`](statsmodels.sandbox.regression.gmm.ivgmmresults.bse#statsmodels.sandbox.regression.gmm.IVGMMResults.bse "statsmodels.sandbox.regression.gmm.IVGMMResults.bse")() | |
| [`calc_cov_params`](statsmodels.sandbox.regression.gmm.ivgmmresults.calc_cov_params#statsmodels.sandbox.regression.gmm.IVGMMResults.calc_cov_params "statsmodels.sandbox.regression.gmm.IVGMMResults.calc_cov_params")(moms, gradmoms[, weights, β¦]) | calculate covariance of parameter estimates |
| [`compare_j`](statsmodels.sandbox.regression.gmm.ivgmmresults.compare_j#statsmodels.sandbox.regression.gmm.IVGMMResults.compare_j "statsmodels.sandbox.regression.gmm.IVGMMResults.compare_j")(other) | overidentification test for comparing two nested gmm estimates |
| [`conf_int`](statsmodels.sandbox.regression.gmm.ivgmmresults.conf_int#statsmodels.sandbox.regression.gmm.IVGMMResults.conf_int "statsmodels.sandbox.regression.gmm.IVGMMResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. |
| [`cov_params`](statsmodels.sandbox.regression.gmm.ivgmmresults.cov_params#statsmodels.sandbox.regression.gmm.IVGMMResults.cov_params "statsmodels.sandbox.regression.gmm.IVGMMResults.cov_params")([r\_matrix, column, scale, cov\_p, β¦]) | Returns the variance/covariance matrix. |
| [`f_test`](statsmodels.sandbox.regression.gmm.ivgmmresults.f_test#statsmodels.sandbox.regression.gmm.IVGMMResults.f_test "statsmodels.sandbox.regression.gmm.IVGMMResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. |
| [`fittedvalues`](statsmodels.sandbox.regression.gmm.ivgmmresults.fittedvalues#statsmodels.sandbox.regression.gmm.IVGMMResults.fittedvalues "statsmodels.sandbox.regression.gmm.IVGMMResults.fittedvalues")() | |
| [`get_bse`](statsmodels.sandbox.regression.gmm.ivgmmresults.get_bse#statsmodels.sandbox.regression.gmm.IVGMMResults.get_bse "statsmodels.sandbox.regression.gmm.IVGMMResults.get_bse")(\*\*kwds) | standard error of the parameter estimates with options |
| [`initialize`](statsmodels.sandbox.regression.gmm.ivgmmresults.initialize#statsmodels.sandbox.regression.gmm.IVGMMResults.initialize "statsmodels.sandbox.regression.gmm.IVGMMResults.initialize")(model, params, \*\*kwd) | |
| [`jtest`](statsmodels.sandbox.regression.gmm.ivgmmresults.jtest#statsmodels.sandbox.regression.gmm.IVGMMResults.jtest "statsmodels.sandbox.regression.gmm.IVGMMResults.jtest")() | overidentification test |
| [`jval`](statsmodels.sandbox.regression.gmm.ivgmmresults.jval#statsmodels.sandbox.regression.gmm.IVGMMResults.jval "statsmodels.sandbox.regression.gmm.IVGMMResults.jval")() | |
| [`llf`](statsmodels.sandbox.regression.gmm.ivgmmresults.llf#statsmodels.sandbox.regression.gmm.IVGMMResults.llf "statsmodels.sandbox.regression.gmm.IVGMMResults.llf")() | |
| [`load`](statsmodels.sandbox.regression.gmm.ivgmmresults.load#statsmodels.sandbox.regression.gmm.IVGMMResults.load "statsmodels.sandbox.regression.gmm.IVGMMResults.load")(fname) | load a pickle, (class method) |
| [`normalized_cov_params`](statsmodels.sandbox.regression.gmm.ivgmmresults.normalized_cov_params#statsmodels.sandbox.regression.gmm.IVGMMResults.normalized_cov_params "statsmodels.sandbox.regression.gmm.IVGMMResults.normalized_cov_params")() | |
| [`predict`](statsmodels.sandbox.regression.gmm.ivgmmresults.predict#statsmodels.sandbox.regression.gmm.IVGMMResults.predict "statsmodels.sandbox.regression.gmm.IVGMMResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. |
| [`pvalues`](statsmodels.sandbox.regression.gmm.ivgmmresults.pvalues#statsmodels.sandbox.regression.gmm.IVGMMResults.pvalues "statsmodels.sandbox.regression.gmm.IVGMMResults.pvalues")() | |
| [`q`](statsmodels.sandbox.regression.gmm.ivgmmresults.q#statsmodels.sandbox.regression.gmm.IVGMMResults.q "statsmodels.sandbox.regression.gmm.IVGMMResults.q")() | |
| [`remove_data`](statsmodels.sandbox.regression.gmm.ivgmmresults.remove_data#statsmodels.sandbox.regression.gmm.IVGMMResults.remove_data "statsmodels.sandbox.regression.gmm.IVGMMResults.remove_data")() | remove data arrays, all nobs arrays from result and model |
| [`resid`](statsmodels.sandbox.regression.gmm.ivgmmresults.resid#statsmodels.sandbox.regression.gmm.IVGMMResults.resid "statsmodels.sandbox.regression.gmm.IVGMMResults.resid")() | |
| [`save`](statsmodels.sandbox.regression.gmm.ivgmmresults.save#statsmodels.sandbox.regression.gmm.IVGMMResults.save "statsmodels.sandbox.regression.gmm.IVGMMResults.save")(fname[, remove\_data]) | save a pickle of this instance |
| [`ssr`](statsmodels.sandbox.regression.gmm.ivgmmresults.ssr#statsmodels.sandbox.regression.gmm.IVGMMResults.ssr "statsmodels.sandbox.regression.gmm.IVGMMResults.ssr")() | |
| [`summary`](statsmodels.sandbox.regression.gmm.ivgmmresults.summary#statsmodels.sandbox.regression.gmm.IVGMMResults.summary "statsmodels.sandbox.regression.gmm.IVGMMResults.summary")([yname, xname, title, alpha]) | Summarize the Regression Results |
| [`t_test`](statsmodels.sandbox.regression.gmm.ivgmmresults.t_test#statsmodels.sandbox.regression.gmm.IVGMMResults.t_test "statsmodels.sandbox.regression.gmm.IVGMMResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q |
| [`t_test_pairwise`](statsmodels.sandbox.regression.gmm.ivgmmresults.t_test_pairwise#statsmodels.sandbox.regression.gmm.IVGMMResults.t_test_pairwise "statsmodels.sandbox.regression.gmm.IVGMMResults.t_test_pairwise")(term\_name[, method, alpha, β¦]) | perform pairwise t\_test with multiple testing corrected p-values |
| [`tvalues`](statsmodels.sandbox.regression.gmm.ivgmmresults.tvalues#statsmodels.sandbox.regression.gmm.IVGMMResults.tvalues "statsmodels.sandbox.regression.gmm.IVGMMResults.tvalues")() | Return the t-statistic for a given parameter estimate. |
| [`wald_test`](statsmodels.sandbox.regression.gmm.ivgmmresults.wald_test#statsmodels.sandbox.regression.gmm.IVGMMResults.wald_test "statsmodels.sandbox.regression.gmm.IVGMMResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, β¦]) | Compute a Wald-test for a joint linear hypothesis. |
| [`wald_test_terms`](statsmodels.sandbox.regression.gmm.ivgmmresults.wald_test_terms#statsmodels.sandbox.regression.gmm.IVGMMResults.wald_test_terms "statsmodels.sandbox.regression.gmm.IVGMMResults.wald_test_terms")([skip\_single, β¦]) | Compute a sequence of Wald tests for terms over multiple columns |
#### Attributes
| | |
| --- | --- |
| `bse_` | standard error of the parameter estimates |
| `use_t` | |
statsmodels statsmodels.sandbox.regression.gmm.GMMResults.bse statsmodels.sandbox.regression.gmm.GMMResults.bse
=================================================
`GMMResults.bse()`
statsmodels statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults statsmodels.tsa.vector\_ar.hypothesis\_test\_results.NormalityTestResults
=========================================================================
`class statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults(test_statistic, crit_value, pvalue, df, signif)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/hypothesis_test_results.html#NormalityTestResults)
Results class for the Jarque-Bera-test for nonnormality.
| Parameters: | * **test\_statistic** (*float*) β The testβs test statistic.
* **crit\_value** (*float*) β The testβs critical value.
* **pvalue** (*float*) β The testβs p-value.
* **df** (*int*) β Degrees of freedom.
* **signif** (*float*) β Significance level.
|
#### Methods
| | |
| --- | --- |
| [`summary`](statsmodels.tsa.vector_ar.hypothesis_test_results.normalitytestresults.summary#statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults.summary "statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults.summary")() | |
statsmodels statsmodels.discrete.discrete_model.BinaryResults.tvalues statsmodels.discrete.discrete\_model.BinaryResults.tvalues
==========================================================
`BinaryResults.tvalues()`
Return the t-statistic for a given parameter estimate.
statsmodels statsmodels.emplike.descriptive.DescStatUV.test_mean statsmodels.emplike.descriptive.DescStatUV.test\_mean
=====================================================
`DescStatUV.test_mean(mu0, return_weights=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV.test_mean)
Returns - 2 x log-likelihood ratio, p-value and weights for a hypothesis test of the mean.
| Parameters: | * **mu0** (*float*) β Mean value to be tested
* **return\_weights** (*bool*) β If return\_weights is True the funtion returns the weights of the observations under the null hypothesis. Default is False
|
| Returns: | **test\_results** β The log-likelihood ratio and p-value of mu0 |
| Return type: | tuple |
statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.freeze statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.freeze
===================================================================
`TransfTwo_gen.freeze(*args, **kwds)`
Freeze the distribution for the given arguments.
| Parameters: | **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution. Should include all the non-optional arguments, may include `loc` and `scale`. |
| Returns: | **rv\_frozen** β The frozen distribution. |
| Return type: | rv\_frozen instance |
statsmodels statsmodels.tsa.holtwinters.Holt.from_formula statsmodels.tsa.holtwinters.Holt.from\_formula
==============================================
`classmethod Holt.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)`
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
| programming_docs |
statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.sf statsmodels.sandbox.distributions.transformed.Transf\_gen.sf
============================================================
`Transf_gen.sf(x, *args, **kwds)`
Survival function (1 - `cdf`) at x of the given RV.
| Parameters: | * **x** (*array\_like*) β quantiles
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
| Returns: | **sf** β Survival function evaluated at x |
| Return type: | array\_like |
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.wald_test_terms statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.wald\_test\_terms
=================================================================================
`DynamicFactorResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)`
Compute a sequence of Wald tests for terms over multiple columns
This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero.
`Terms` are defined by the underlying formula or by string matching.
| Parameters: | * **skip\_single** (*boolean*) β If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included.
* **extra\_constraints** (*ndarray*) β not tested yet
* **combine\_terms** (*None* *or* *list of strings*) β Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test.
|
| Returns: | **test\_result** β The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. |
| Return type: | result instance |
#### Examples
```
>>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit()
>>> res_ols.wald_test_terms()
<class 'statsmodels.stats.contrast.WaldTestResults'>
F P>F df constraint df denom
Intercept 279.754525 2.37985521351e-22 1 51
C(Duration, Sum) 5.367071 0.0245738436636 1 51
C(Weight, Sum) 12.432445 3.99943118767e-05 2 51
C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51
```
```
>>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0')
>>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight'])
>>> print(wt)
chi2 P>chi2 df constraint
Intercept 15.695625 7.43960374424e-05 1
C(Weight) 16.132616 0.000313940174705 2
C(Duration) 1.009147 0.315107378931 1
C(Weight):C(Duration) 0.216694 0.897315972824 2
Duration 11.187849 0.010752286833 3
Weight 30.263368 4.32586407145e-06 4
```
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.hqic statsmodels.tsa.statespace.mlemodel.MLEResults.hqic
===================================================
`MLEResults.hqic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.hqic)
(float) Hannan-Quinn Information Criterion
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.test_inst_causality statsmodels.tsa.vector\_ar.var\_model.VARResults.test\_inst\_causality
======================================================================
`VARResults.test_inst_causality(causing, signif=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.test_inst_causality)
Test for instantaneous causality
| Parameters: | * **causing** β If int or str, test whether the corresponding variable is causing the variable(s) specified in caused. If sequence of int or str, test whether the corresponding variables are causing the variable(s) specified in caused.
* **signif** (*float between 0 and 1**,* *default 5 %*) β Significance level for computing critical values for test, defaulting to standard 0.05 level
* **verbose** (*bool*) β If True, print a table with the results.
|
| Returns: | **results** β A dict holding the testβs results. The dictβs keys are:
`βstatisticβ : float`
The calculated test statistic.
`βcrit_valueβ : float`
The critical value of the Chi^2-distribution.
`βpvalueβ : float`
The p-value corresponding to the test statistic.
`βdfβ : float`
The degrees of freedom of the Chi^2-distribution.
`βconclusionβ : str {βrejectβ, βfail to rejectβ}`
Whether H0 can be rejected or not.
`βsignifβ : float`
Significance level |
| Return type: | [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") |
#### Notes
Test for instantaneous causality as described in chapters 3.6.3 and 7.6.4 of [[1]](#id3). Test H0: βNo instantaneous causality between caused and causingβ against H1: βInstantaneous causality between caused and causing existsβ.
Instantaneous causality is a symmetric relation (i.e. if causing is βinstantaneously causingβ caused, then also caused is βinstantaneously causingβ causing), thus the naming of the parameters (which is chosen to be in accordance with test\_granger\_causality()) may be misleading.
This method is not returning the same result as JMulTi. This is because the test is based on a VAR(k\_ar) model in statsmodels (in accordance to pp. 104, 320-321 in [[1]](#id3)) whereas JMulTi seems to be using a VAR(k\_ar+1) model.
#### References
| | |
| --- | --- |
| [1] | *([1](#id1), [2](#id2))* LΓΌtkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer. |
statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.predict statsmodels.tsa.statespace.varmax.VARMAXResults.predict
=======================================================
`VARMAXResults.predict(start=None, end=None, dynamic=False, **kwargs)`
In-sample prediction and out-of-sample forecasting
| Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation.
* **end** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample.
* **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) β Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead.
* **\*\*kwargs** β Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details.
|
| Returns: | **forecast** β Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k\_endog) array. |
| Return type: | array |
statsmodels statsmodels.stats.stattools.medcouple statsmodels.stats.stattools.medcouple
=====================================
`statsmodels.stats.stattools.medcouple(y, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/stattools.html#medcouple)
Calculates the medcouple robust measure of skew.
| Parameters: | * **y** (*array-like*) β
* **axis** (*int* *or* *None**,* *optional*) β Axis along which the medcouple statistic is computed. If `None`, the entire array is used.
|
| Returns: | **mc** β The medcouple statistic with the same shape as `y`, with the specified axis removed. |
| Return type: | ndarray |
#### Notes
The current algorithm requires a O(N\*\*2) memory allocations, and so may not work for very large arrays (N>10000).
| | |
| --- | --- |
| [\*] | M. Huberta and E. Vandervierenb, βAn adjusted boxplot for skewed distributionsβ Computational Statistics & Data Analysis, vol. 52, pp. 5186-5201, August 2008. |
statsmodels statsmodels.duration.survfunc.SurvfuncRight.simultaneous_cb statsmodels.duration.survfunc.SurvfuncRight.simultaneous\_cb
============================================================
`SurvfuncRight.simultaneous_cb(alpha=0.05, method='hw', transform='log')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/survfunc.html#SurvfuncRight.simultaneous_cb)
Returns a simultaneous confidence band for the survival function.
| Parameters: | * **alpha** (*float*) β `1 - alpha` is the desired simultaneous coverage probability for the confidence region. Currently alpha must be set to 0.05, giving 95% simultaneous intervals.
* **method** (*string*) β The method used to produce the simultaneous confidence band. Only the Hall-Wellner (hw) method is currently implemented.
* **transform** (*string*) β The used to produce the interval (note that the returned interval is on the survival probability scale regardless of which transform is used). Only `log` and `arcsin` are implemented.
|
| Returns: | * **lcb** (*array-like*) β The lower confidence limits corresponding to the points in `surv_times`.
* **ucb** (*array-like*) β The upper confidence limits corresponding to the points in `surv_times`.
|
statsmodels statsmodels.nonparametric.kernel_regression.KernelCensoredReg.censored statsmodels.nonparametric.kernel\_regression.KernelCensoredReg.censored
=======================================================================
`KernelCensoredReg.censored(censor_val)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_regression.html#KernelCensoredReg.censored)
statsmodels statsmodels.sandbox.distributions.transformed.absnormalg statsmodels.sandbox.distributions.transformed.absnormalg
========================================================
`statsmodels.sandbox.distributions.transformed.absnormalg = <statsmodels.sandbox.distributions.transformed.TransfTwo_gen object>`
Distribution based on a non-monotonic (u- or hump-shaped transformation)
the constructor can be called with a distribution class, and functions that define the non-linear transformation. and generates the distribution of the transformed random variable
Note: the transformation, itβs inverse and derivatives need to be fully specified: func, funcinvplus, funcinvminus, derivplus, derivminus. Currently no numerical derivatives or inverse are calculated
This can be used to generate distribution instances similar to the distributions in scipy.stats.
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.wald_test_terms statsmodels.tsa.statespace.mlemodel.MLEResults.wald\_test\_terms
================================================================
`MLEResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)`
Compute a sequence of Wald tests for terms over multiple columns
This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero.
`Terms` are defined by the underlying formula or by string matching.
| Parameters: | * **skip\_single** (*boolean*) β If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included.
* **extra\_constraints** (*ndarray*) β not tested yet
* **combine\_terms** (*None* *or* *list of strings*) β Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test.
|
| Returns: | **test\_result** β The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. |
| Return type: | result instance |
#### Examples
```
>>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit()
>>> res_ols.wald_test_terms()
<class 'statsmodels.stats.contrast.WaldTestResults'>
F P>F df constraint df denom
Intercept 279.754525 2.37985521351e-22 1 51
C(Duration, Sum) 5.367071 0.0245738436636 1 51
C(Weight, Sum) 12.432445 3.99943118767e-05 2 51
C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51
```
```
>>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0')
>>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight'])
>>> print(wt)
chi2 P>chi2 df constraint
Intercept 15.695625 7.43960374424e-05 1
C(Weight) 16.132616 0.000313940174705 2
C(Duration) 1.009147 0.315107378931 1
C(Weight):C(Duration) 0.216694 0.897315972824 2
Duration 11.187849 0.010752286833 3
Weight 30.263368 4.32586407145e-06 4
```
statsmodels statsmodels.robust.robust_linear_model.RLMResults.sresid statsmodels.robust.robust\_linear\_model.RLMResults.sresid
==========================================================
`RLMResults.sresid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLMResults.sresid)
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params statsmodels.regression.recursive\_ls.RecursiveLSResults.cov\_params
===================================================================
`RecursiveLSResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)`
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar.
| Parameters: | * **r\_matrix** (*array-like*) β Can be 1d, or 2d. Can be used alone or with other.
* **column** (*array-like**,* *optional*) β Must be used on its own. Can be 0d or 1d see below.
* **scale** (*float**,* *optional*) β Can be specified or not. Default is None, which means that the scale argument is taken from the model.
* **other** (*array-like**,* *optional*) β Can be used when r\_matrix is specified.
|
| Returns: | **cov** β covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. |
| Return type: | ndarray |
#### Notes
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)`
If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T`
If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T`
If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d
OR
`(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust_approx statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov\_params\_robust\_approx
=============================================================================================
`UnobservedComponentsResults.cov_params_robust_approx()`
(array) The QMLE variance / covariance matrix. Computed using the numerical Hessian as the evaluated hessian.
statsmodels statsmodels.sandbox.stats.runs.runstest_1samp statsmodels.sandbox.stats.runs.runstest\_1samp
==============================================
`statsmodels.sandbox.stats.runs.runstest_1samp(x, cutoff='mean', correction=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/runs.html#runstest_1samp)
use runs test on binary discretized data above/below cutoff
| Parameters: | * **x** (*array\_like*) β data, numeric
* **cutoff** (*{'mean'**,* *'median'}* *or* *number*) β This specifies the cutoff to split the data into large and small values.
* **correction** (*bool*) β Following the SAS manual, for samplesize below 50, the test statistic is corrected by 0.5. This can be turned off with correction=False, and was included to match R, tseries, which does not use any correction.
|
| Returns: | * **z\_stat** (*float*) β test statistic, asymptotically normally distributed
* **p-value** (*float*) β p-value, reject the null hypothesis if it is below an type 1 error level, alpha .
|
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.ma_rep statsmodels.tsa.vector\_ar.var\_model.VARResults.ma\_rep
========================================================
`VARResults.ma_rep(maxn=10)`
Compute MA(\(\infty\)) coefficient matrices
| Parameters: | **maxn** (*int*) β Number of coefficient matrices to compute |
| Returns: | **coefs** |
| Return type: | ndarray (maxn x k x k) |
statsmodels statsmodels.discrete.discrete_model.Poisson.fit_constrained statsmodels.discrete.discrete\_model.Poisson.fit\_constrained
=============================================================
`Poisson.fit_constrained(constraints, start_params=None, **fit_kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.fit_constrained)
fit the model subject to linear equality constraints
The constraints are of the form `R params = q` where R is the constraint\_matrix and q is the vector of constraint\_values.
The estimation creates a new model with transformed design matrix, exog, and converts the results back to the original parameterization.
| Parameters: | * **constraints** (*formula expression* *or* *tuple*) β If it is a tuple, then the constraint needs to be given by two arrays (constraint\_matrix, constraint\_value), i.e. (R, q). Otherwise, the constraints can be given as strings or list of strings. see t\_test for details
* **start\_params** (*None* *or* *array\_like*) β starting values for the optimization. `start_params` needs to be given in the original parameter space and are internally transformed.
* **\*\*fit\_kwds** (*keyword arguments*) β fit\_kwds are used in the optimization of the transformed model.
|
| Returns: | **results** |
| Return type: | Results instance |
statsmodels statsmodels.stats.stattools.durbin_watson statsmodels.stats.stattools.durbin\_watson
==========================================
`statsmodels.stats.stattools.durbin_watson(resids, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/stattools.html#durbin_watson)
Calculates the Durbin-Watson statistic
| Parameters: | **resids** (*array-like*) β |
| Returns: | * **dw** (*float, array-like*)
* *The Durbin-Watson statistic.*
|
#### Notes
The null hypothesis of the test is that there is no serial correlation. The Durbin-Watson test statistics is defined as:
\[\sum\_{t=2}^T((e\_t - e\_{t-1})^2)/\sum\_{t=1}^Te\_t^2\] The test statistic is approximately equal to 2\*(1-r) where `r` is the sample autocorrelation of the residuals. Thus, for r == 0, indicating no serial correlation, the test statistic equals 2. This statistic will always be between 0 and 4. The closer to 0 the statistic, the more evidence for positive serial correlation. The closer to 4, the more evidence for negative serial correlation.
| programming_docs |
statsmodels statsmodels.genmod.families.family.Family.deviance statsmodels.genmod.families.family.Family.deviance
==================================================
`Family.deviance(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Family.deviance)
The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution.
Deviance is usually defined as twice the loglikelihood ratio.
| Parameters: | * **endog** (*array-like*) β The endogenous response variable
* **mu** (*array-like*) β The inverse of the link function at the linear predicted values.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **freq\_weights** (*array-like*) β 1d array of frequency weights. The default is 1.
* **scale** (*float**,* *optional*) β An optional scale argument. The default is 1.
|
| Returns: | **Deviance** β The value of deviance function defined below. |
| Return type: | array |
#### Notes
Deviance is defined
\[D = 2\sum\_i (freq\\_weights\_i \* var\\_weights \* (llf(endog\_i, endog\_i) - llf(endog\_i, \mu\_i)))\] where y is the endogenous variable. The deviance functions are analytically defined for each family.
Internally, we calculate deviance as:
\[D = \sum\_i freq\\_weights\_i \* var\\_weights \* resid\\_dev\_i / scale\]
statsmodels statsmodels.regression.quantile_regression.QuantRegResults.get_prediction statsmodels.regression.quantile\_regression.QuantRegResults.get\_prediction
===========================================================================
`QuantRegResults.get_prediction(exog=None, transform=True, weights=None, row_labels=None, **kwds)`
compute prediction results
| Parameters: | * **exog** (*array-like**,* *optional*) β The values for which you want to predict.
* **transform** (*bool**,* *optional*) β If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, youβd need to log the data first.
* **weights** (*array\_like**,* *optional*) β Weights interpreted as in WLS, used for the variance of the predicted residual.
* **kwargs** (*args**,*) β Some models can take additional arguments or keywords, see the predict method of the model for the details.
|
| Returns: | **prediction\_results** β The prediction results instance contains prediction and prediction variance and can on demand calculate confidence intervals and summary tables for the prediction of the mean and of new observations. |
| Return type: | [linear\_model.PredictionResults](statsmodels.regression.linear_model.predictionresults#statsmodels.regression.linear_model.PredictionResults "statsmodels.regression.linear_model.PredictionResults") |
statsmodels statsmodels.tsa.vector_ar.vecm.VECM.score statsmodels.tsa.vector\_ar.vecm.VECM.score
==========================================
`VECM.score(params)`
Score vector of model.
The gradient of logL with respect to each parameter.
statsmodels statsmodels.nonparametric.kde.KDEUnivariate.icdf statsmodels.nonparametric.kde.KDEUnivariate.icdf
================================================
`KDEUnivariate.icdf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kde.html#KDEUnivariate.icdf)
Inverse Cumulative Distribution (Quantile) Function
#### Notes
Will not work if fit has not been called. Uses `scipy.stats.mstats.mquantiles`.
statsmodels statsmodels.discrete.discrete_model.MultinomialModel.fit_regularized statsmodels.discrete.discrete\_model.MultinomialModel.fit\_regularized
======================================================================
`MultinomialModel.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MultinomialModel.fit_regularized)
Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method.
| Parameters: | * **start\_params** (*array-like**,* *optional*) β Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros.
* **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) β See notes for details.
* **maxiter** (*Integer* *or* *'defined\_by\_method'*) β Maximum number of iterations to perform. If βdefined\_by\_methodβ, then use method defaults (see notes).
* **full\_output** (*bool*) β Set to True to have all available output in the Results objectβs mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information.
* **disp** (*bool*) β Set to True to print convergence messages.
* **fargs** (*tuple*) β Extra arguments passed to the likelihood function, i.e., loglike(x,\*args)
* **callback** (*callable callback**(**xk**)*) β Called after each iteration, as callback(xk), where xk is the current parameter vector.
* **retall** (*bool*) β Set to True to return list of solutions at each iteration. Available in Results objectβs mle\_retvals attribute.
* **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) β The weight multiplying the l1 penalty term
* **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) β If not βoffβ, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If βautoβ, trim params using the Theory above. If βsizeβ, trim params if they have very small absolute value
* **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) β For use when trim\_mode == βsizeβ
* **auto\_trim\_tol** (*float*) β For sue when trim\_mode == βautoβ. Use
* **qc\_tol** (*float*) β Print warning and donβt allow auto trim when (ii) (above) is violated by this much.
* **qc\_verbose** (*Boolean*) β If true, print out a full QC report upon failure
|
#### Notes
Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`.
Optional arguments for the solvers (available in Results.mle\_settings):
```
'l1'
acc : float (default 1e-6)
Requested accuracy as used by slsqp
'l1_cvxopt_cp'
abstol : float
absolute accuracy (default: 1e-7).
reltol : float
relative accuracy (default: 1e-6).
feastol : float
tolerance for feasibility conditions (default: 1e-7).
refinement : int
number of iterative refinement steps when solving KKT
equations (default: 1).
```
Optimization methodology
With \(L\) the negative log likelihood, we solve the convex but non-smooth problem
\[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the βadded variablesβ \(u\_k\))
\[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to
\[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds:
1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\)
2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\)
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoisson.fit statsmodels.discrete.count\_model.ZeroInflatedPoisson.fit
=========================================================
`ZeroInflatedPoisson.fit(start_params=None, method='bfgs', maxiter=35, full_output=1, disp=1, callback=None, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)`
Fit the model using maximum likelihood.
The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit
Fit method for likelihood based models
| Parameters: | * **start\_params** (*array-like**,* *optional*) β Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros.
* **method** (*str**,* *optional*) β The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings:
+ βnewtonβ for Newton-Raphson, βnmβ for Nelder-Mead
+ βbfgsβ for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
+ βlbfgsβ for limited-memory BFGS with optional box constraints
+ βpowellβ for modified Powellβs method
+ βcgβ for conjugate gradient
+ βncgβ for Newton-conjugate gradient
+ βbasinhoppingβ for global basin-hopping solver
+ βminimizeβ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports.
* **maxiter** (*int**,* *optional*) β The maximum number of iterations to perform.
* **full\_output** (*bool**,* *optional*) β Set to True to have all available output in the Results objectβs mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information.
* **disp** (*bool**,* *optional*) β Set to True to print convergence messages.
* **fargs** (*tuple**,* *optional*) β Extra arguments passed to the likelihood function, i.e., loglike(x,\*args)
* **callback** (*callable callback**(**xk**)**,* *optional*) β Called after each iteration, as callback(xk), where xk is the current parameter vector.
* **retall** (*bool**,* *optional*) β Set to True to return list of solutions at each iteration. Available in Results objectβs mle\_retvals attribute.
* **skip\_hessian** (*bool**,* *optional*) β If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `βnewtonβ`).
* **kwargs** (*keywords*) β All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit:
```
warn_convergence : bool, optional
If True, checks the model for the converged flag. If the
converged flag is False, a ConvergenceWarning is issued.
```
|
#### Notes
The βbasinhoppingβ solver ignores `maxiter`, `retall`, `full_output` explicit arguments.
Optional arguments for solvers (see returned Results.mle\_settings):
```
'newton'
tol : float
Relative error in params acceptable for convergence.
'nm' -- Nelder Mead
xtol : float
Relative error in params acceptable for convergence
ftol : float
Relative error in loglike(params) acceptable for
convergence
maxfun : int
Maximum number of function evaluations to make.
'bfgs'
gtol : float
Stop when norm of gradient is less than gtol.
norm : float
Order of norm (np.Inf is max, -np.Inf is min)
epsilon
If fprime is approximated, use this value for the step
size. Only relevant if LikelihoodModel.score is None.
'lbfgs'
m : int
This many terms are used for the Hessian approximation.
factr : float
A stop condition that is a variant of relative error.
pgtol : float
A stop condition that uses the projected gradient.
epsilon
If fprime is approximated, use this value for the step
size. Only relevant if LikelihoodModel.score is None.
maxfun : int
Maximum number of function evaluations to make.
bounds : sequence
(min, max) pairs for each element in x,
defining the bounds on that parameter.
Use None for one of min or max when there is no bound
in that direction.
'cg'
gtol : float
Stop when norm of gradient is less than gtol.
norm : float
Order of norm (np.Inf is max, -np.Inf is min)
epsilon : float
If fprime is approximated, use this value for the step
size. Can be scalar or vector. Only relevant if
Likelihoodmodel.score is None.
'ncg'
fhess_p : callable f'(x,*args)
Function which computes the Hessian of f times an arbitrary
vector, p. Should only be supplied if
LikelihoodModel.hessian is None.
avextol : float
Stop when the average relative error in the minimizer
falls below this amount.
epsilon : float or ndarray
If fhess is approximated, use this value for the step size.
Only relevant if Likelihoodmodel.hessian is None.
'powell'
xtol : float
Line-search error tolerance
ftol : float
Relative error in loglike(params) for acceptable for
convergence.
maxfun : int
Maximum number of function evaluations to make.
start_direc : ndarray
Initial direction set.
'basinhopping'
niter : integer
The number of basin hopping iterations.
niter_success : integer
Stop the run if the global minimum candidate remains the
same for this number of iterations.
T : float
The "temperature" parameter for the accept or reject
criterion. Higher "temperatures" mean that larger jumps
in function value will be accepted. For best results
`T` should be comparable to the separation (in function
value) between local minima.
stepsize : float
Initial step size for use in the random displacement.
interval : integer
The interval for how often to update the `stepsize`.
minimizer : dict
Extra keyword arguments to be passed to the minimizer
`scipy.optimize.minimize()`, for example 'method' - the
minimization method (e.g. 'L-BFGS-B'), or 'tol' - the
tolerance for termination. Other arguments are mapped from
explicit argument of `fit`:
- `args` <- `fargs`
- `jac` <- `score`
- `hess` <- `hess`
'minimize'
min_method : str, optional
Name of minimization method to use.
Any method specific arguments can be passed directly.
For a list of methods and their arguments, see
documentation of `scipy.optimize.minimize`.
If no method is specified, then BFGS is used.
```
statsmodels statsmodels.tsa.arima_process.arma_acf statsmodels.tsa.arima\_process.arma\_acf
========================================
`statsmodels.tsa.arima_process.arma_acf(ar, ma, lags=10, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#arma_acf)
Theoretical autocorrelation function of an ARMA process
| Parameters: | * **ar** (*array\_like**,* *1d*) β coefficient for autoregressive lag polynomial, including zero lag
* **ma** (*array\_like**,* *1d*) β coefficient for moving-average lag polynomial, including zero lag
* **lags** (*int*) β number of terms (lags plus zero lag) to include in returned acf
|
| Returns: | **acf** β autocorrelation of ARMA process given by ar, ma |
| Return type: | array |
See also
[`arma_acovf`](statsmodels.tsa.arima_process.arma_acovf#statsmodels.tsa.arima_process.arma_acovf "statsmodels.tsa.arima_process.arma_acovf"), `acf`, `acovf`
statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.loglike statsmodels.discrete.discrete\_model.NegativeBinomial.loglike
=============================================================
`NegativeBinomial.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomial.loglike)
Loglikelihood for negative binomial model
| Parameters: | **params** (*array-like*) β The parameters of the model. If `loglike_method` is nb1 or nb2, then the ancillary parameter is expected to be the last element. |
| Returns: | **llf** β The loglikelihood value at `params` |
| Return type: | float |
#### Notes
Following notation in Greene (2008), with negative binomial heterogeneity parameter \(\alpha\):
\[\begin{split}\lambda\_i &= exp(X\beta) \\ \theta &= 1 / \alpha \\ g\_i &= \theta \lambda\_i^Q \\ w\_i &= g\_i/(g\_i + \lambda\_i) \\ r\_i &= \theta / (\theta+\lambda\_i) \\ ln \mathcal{L}\_i &= ln \Gamma(y\_i+g\_i) - ln \Gamma(1+y\_i) + g\_iln (r\_i) + y\_i ln(1-r\_i)\end{split}\] where :math`Q=0` for NB2 and geometric and \(Q=1\) for NB1. For the geometric, \(\alpha=0\) as well.
statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_inversion_method statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.set\_inversion\_method
=============================================================================
`KalmanFilter.set_inversion_method(inversion_method=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#KalmanFilter.set_inversion_method)
Set the inversion method
The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed.
| Parameters: | * **inversion\_method** (*integer**,* *optional*) β Bitmask value to set the inversion method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the inversion method by setting individual boolean flags. See notes for details.
|
#### Notes
The inversion method is defined by a collection of boolean flags, and is internally stored as a bitmask. The methods available are:
INVERT\_UNIVARIATE = 0x01 If the endogenous time series is univariate, then inversion can be performed by simple division. If this flag is set and the time series is univariate, then division will always be used even if other flags are also set. SOLVE\_LU = 0x02 Use an LU decomposition along with a linear solver (rather than ever actually inverting the matrix). INVERT\_LU = 0x04 Use an LU decomposition along with typical matrix inversion. SOLVE\_CHOLESKY = 0x08 Use a Cholesky decomposition along with a linear solver. INVERT\_CHOLESKY = 0x10 Use an Cholesky decomposition along with typical matrix inversion. If the bitmask is set directly via the `inversion_method` argument, then the full method must be provided.
If keyword arguments are used to set individual boolean flags, then the lowercase of the method must be used as an argument name, and the value is the desired value of the boolean flag (True or False).
Note that the inversion method may also be specified by directly modifying the class attributes which are defined similarly to the keyword arguments.
The default inversion method is `INVERT_UNIVARIATE | SOLVE_CHOLESKY`
Several things to keep in mind are:
* If the filtering method is specified to be univariate, then simple division is always used regardless of the dimension of the endogenous time series.
* Cholesky decomposition is about twice as fast as LU decomposition, but it requires that the matrix be positive definite. While this should generally be true, it may not be in every case.
* Using a linear solver rather than true matrix inversion is generally faster and is numerically more stable.
#### Examples
```
>>> mod = sm.tsa.statespace.SARIMAX(range(10))
>>> mod.ssm.inversion_method
1
>>> mod.ssm.solve_cholesky
True
>>> mod.ssm.invert_univariate
True
>>> mod.ssm.invert_lu
False
>>> mod.ssm.invert_univariate = False
>>> mod.ssm.inversion_method
8
>>> mod.ssm.set_inversion_method(solve_cholesky=False,
... invert_cholesky=True)
>>> mod.ssm.inversion_method
16
```
statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fitgmm statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fitgmm
========================================================
`NonlinearIVGMM.fitgmm(start, weights=None, optim_method='bfgs', optim_args=None)`
estimate parameters using GMM
| Parameters: | * **start** (*array\_like*) β starting values for minimization
* **weights** (*array*) β weighting matrix for moment conditions. If weights is None, then the identity matrix is used
|
| Returns: | **paramest** β estimated parameters |
| Return type: | array |
#### Notes
todo: add fixed parameter option, not here ???
uses scipy.optimize.fmin
| programming_docs |
statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.pvalues statsmodels.genmod.generalized\_linear\_model.GLMResults.pvalues
================================================================
`GLMResults.pvalues()`
statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.hessian statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.hessian
=====================================================================================
`MarkovAutoregression.hessian(params, transformed=True)`
Hessian matrix of the likelihood function, evaluated at the given parameters
| Parameters: | * **params** (*array\_like*) β Array of parameters at which to evaluate the Hessian function.
* **transformed** (*boolean**,* *optional*) β Whether or not `params` is already transformed. Default is True.
|
statsmodels statsmodels.robust.robust_linear_model.RLMResults.conf_int statsmodels.robust.robust\_linear\_model.RLMResults.conf\_int
=============================================================
`RLMResults.conf_int(alpha=0.05, cols=None, method='default')`
Returns the confidence interval of the fitted parameters.
| Parameters: | * **alpha** (*float**,* *optional*) β The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval.
* **cols** (*array-like**,* *optional*) β `cols` specifies which confidence intervals to return
* **method** (*string*) β Not Implemented Yet Method to estimate the confidence\_interval. βDefaultβ : uses self.bse which is based on inverse Hessian for MLE βhjjhβ : βjacβ : βboot-bseβ βboot\_quantβ βprofileβ
|
| Returns: | **conf\_int** β Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. |
| Return type: | array |
#### Examples
```
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> results.conf_int()
array([[-5496529.48322745, -1467987.78596704],
[ -177.02903529, 207.15277984],
[ -0.1115811 , 0.03994274],
[ -3.12506664, -0.91539297],
[ -1.5179487 , -0.54850503],
[ -0.56251721, 0.460309 ],
[ 798.7875153 , 2859.51541392]])
```
```
>>> results.conf_int(cols=(2,3))
array([[-0.1115811 , 0.03994274],
[-3.12506664, -0.91539297]])
```
#### Notes
The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method.
statsmodels statsmodels.genmod.families.family.Gaussian.loglike_obs statsmodels.genmod.families.family.Gaussian.loglike\_obs
========================================================
`Gaussian.loglike_obs(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Gaussian.loglike_obs)
The log-likelihood function for each observation in terms of the fitted mean response for the Gaussian distribution.
| Parameters: | * **endog** (*array*) β Usually the endogenous response variable.
* **mu** (*array*) β Usually but not always the fitted mean response variable.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **scale** (*float*) β The scale parameter. The default is 1.
|
| Returns: | **ll\_i** β The value of the loglikelihood evaluated at (endog, mu, var\_weights, scale) as defined below. |
| Return type: | float |
#### Notes
If the link is the identity link function then the loglikelihood function is the same as the classical OLS model.
\[llf = -nobs / 2 \* (\log(SSR) + (1 + \log(2 \pi / nobs)))\] where
\[SSR = \sum\_i (Y\_i - g^{-1}(\mu\_i))^2\] If the links is not the identity link then the loglikelihood function is defined as
\[ll\_i = -1 / 2 \sum\_i \* var\\_weights \* ((Y\_i - mu\_i)^2 / scale + \log(2 \* \pi \* scale))\]
statsmodels statsmodels.tools.eval_measures.bic_sigma statsmodels.tools.eval\_measures.bic\_sigma
===========================================
`statsmodels.tools.eval_measures.bic_sigma(sigma2, nobs, df_modelwc, islog=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#bic_sigma)
Bayesian information criterion (BIC) or Schwarz criterion
| Parameters: | * **sigma2** (*float*) β estimate of the residual variance or determinant of Sigma\_hat in the multivariate case. If islog is true, then it is assumed that sigma is already log-ed, for example logdetSigma.
* **nobs** (*int*) β number of observations
* **df\_modelwc** (*int*) β number of parameters including constant
|
| Returns: | **bic** β information criterion |
| Return type: | float |
#### Notes
A constant has been dropped in comparison to the loglikelihood base information criteria. These should be used to compare for comparable models.
#### References
<http://en.wikipedia.org/wiki/Bayesian_information_criterion>
statsmodels statsmodels.regression.linear_model.OLSResults.t_test statsmodels.regression.linear\_model.OLSResults.t\_test
=======================================================
`OLSResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)`
Compute a t-test for a each linear hypothesis of the form Rb = q
| Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) β
+ array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β An optional `scale` to use. Default is the scale specified by the model fit.
* **use\_t** (*bool**,* *optional*) β If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution.
|
| Returns: | **res** β The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. |
| Return type: | ContrastResults instance |
#### Examples
```
>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> results = sm.OLS(data.endog, data.exog).fit()
>>> r = np.zeros_like(results.params)
>>> r[5:] = [1,-1]
>>> print(r)
[ 0. 0. 0. 0. 0. 1. -1.]
```
r tests that the coefficients on the 5th and 6th independent variable are the same.
```
>>> T_test = results.t_test(r)
>>> print(T_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037
==============================================================================
>>> T_test.effect
-1829.2025687192481
>>> T_test.sd
455.39079425193762
>>> T_test.tvalue
-4.0167754636411717
>>> T_test.pvalue
0.0015163772380899498
```
Alternatively, you can specify the hypothesis tests using a string
```
>>> from statsmodels.formula.api import ols
>>> dta = sm.datasets.longley.load_pandas().data
>>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR'
>>> results = ols(formula, dta).fit()
>>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1'
>>> t_test = results.t_test(hypotheses)
>>> print(t_test)
Test for Constraints
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
c0 15.0977 84.937 0.178 0.863 -177.042 207.238
c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915
c2 1.0001 0.249 0.000 1.000 0.437 1.563
==============================================================================
```
See also
[`tvalues`](statsmodels.regression.linear_model.olsresults.tvalues#statsmodels.regression.linear_model.OLSResults.tvalues "statsmodels.regression.linear_model.OLSResults.tvalues")
individual t statistics
[`f_test`](statsmodels.regression.linear_model.olsresults.f_test#statsmodels.regression.linear_model.OLSResults.f_test "statsmodels.regression.linear_model.OLSResults.f_test")
for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
statsmodels statsmodels.genmod.families.family.InverseGaussian.resid_anscombe statsmodels.genmod.families.family.InverseGaussian.resid\_anscombe
==================================================================
`InverseGaussian.resid_anscombe(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#InverseGaussian.resid_anscombe)
The Anscombe residuals
| Parameters: | * **endog** (*array*) β The endogenous response variable
* **mu** (*array*) β The inverse of the link function at the linear predicted values.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **scale** (*float**,* *optional*) β An optional argument to divide the residuals by sqrt(scale). The default is 1.
|
| Returns: | **resid\_anscombe** β The Anscombe residuals for the inverse Gaussian distribution as defined below |
| Return type: | array |
#### Notes
\[resid\\_anscombe\_i = \log(Y\_i / \mu\_i) / \sqrt{\mu\_i \* scale} \* \sqrt(var\\_weights)\]
statsmodels statsmodels.miscmodels.tmodel.TLinearModel.hessian statsmodels.miscmodels.tmodel.TLinearModel.hessian
==================================================
`TLinearModel.hessian(params)`
Hessian of log-likelihood evaluated at params
statsmodels statsmodels.tsa.varma_process.VarmaPoly.getisinvertible statsmodels.tsa.varma\_process.VarmaPoly.getisinvertible
========================================================
`VarmaPoly.getisinvertible(a=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/varma_process.html#VarmaPoly.getisinvertible)
check whether the auto-regressive lag-polynomial is stationary
| Returns: | * **isinvertible** (*boolean*)
* *\*attaches\**
* **maeigenvalues** (*complex array*) β eigenvalues sorted by absolute value
|
#### References
formula taken from NAG manual
statsmodels statsmodels.iolib.table.SimpleTable.insert_stubs statsmodels.iolib.table.SimpleTable.insert\_stubs
=================================================
`SimpleTable.insert_stubs(loc, stubs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.insert_stubs)
Return None. Insert column of stubs at column `loc`. If there is a header row, it gets an empty cell. So `len(stubs)` should equal the number of non-header rows.
statsmodels statsmodels.tsa.statespace.kalman_filter.FilterResults.update_filter statsmodels.tsa.statespace.kalman\_filter.FilterResults.update\_filter
======================================================================
`FilterResults.update_filter(kalman_filter)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#FilterResults.update_filter)
Update the filter results
| Parameters: | **kalman\_filter** ([statespace.kalman\_filter.KalmanFilter](statsmodels.tsa.statespace.kalman_filter.kalmanfilter#statsmodels.tsa.statespace.kalman_filter.KalmanFilter "statsmodels.tsa.statespace.kalman_filter.KalmanFilter")) β The model object from which to take the updated values. |
#### Notes
This method is rarely required except for internal usage.
statsmodels statsmodels.sandbox.stats.multicomp.catstack statsmodels.sandbox.stats.multicomp.catstack
============================================
`statsmodels.sandbox.stats.multicomp.catstack(args)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#catstack)
statsmodels statsmodels.nonparametric.kde.KDEUnivariate.evaluate statsmodels.nonparametric.kde.KDEUnivariate.evaluate
====================================================
`KDEUnivariate.evaluate(point)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kde.html#KDEUnivariate.evaluate)
Evaluate density at a single point.
| Parameters: | **point** (*float*) β Point at which to evaluate the density. |
statsmodels statsmodels.duration.hazard_regression.PHReg.predict statsmodels.duration.hazard\_regression.PHReg.predict
=====================================================
`PHReg.predict(params, exog=None, cov_params=None, endog=None, strata=None, offset=None, pred_type='lhr')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.predict)
Returns predicted values from the proportional hazards regression model.
| Parameters: | * **params** (*array-like*) β The proportional hazards model parameters.
* **exog** (*array-like*) β Data to use as `exog` in forming predictions. If not provided, the `exog` values from the model used to fit the data are used.
* **cov\_params** (*array-like*) β The covariance matrix of the estimated `params` vector, used to obtain prediction errors if pred\_type=βlhrβ, otherwise optional.
* **endog** (*array-like*) β Duration (time) values at which the predictions are made. Only used if pred\_type is either βcumhazβ or βsurvβ. If using model `exog`, defaults to model `endog` (time), but may be provided explicitly to make predictions at alternative times.
* **strata** (*array-like*) β A vector of stratum values used to form the predictions. Not used (may be βNoneβ) if pred\_type is βlhrβ or βhrβ. If `exog` is None, the model stratum values are used. If `exog` is not None and pred\_type is βsurvβ or βcumhazβ, stratum values must be provided (unless there is only one stratum).
* **offset** (*array-like*) β Offset values used to create the predicted values.
* **pred\_type** (*string*) β If βlhrβ, returns log hazard ratios, if βhrβ returns hazard ratios, if βsurvβ returns the survival function, if βcumhazβ returns the cumulative hazard function.
|
| Returns: | * **A bunch containing two fields** (`predicted_values` and)
* `standard_errors`.
|
#### Notes
Standard errors are only returned when predicting the log hazard ratio (pred\_type is βlhrβ).
Types `surv` and `cumhaz` require estimation of the cumulative hazard function.
statsmodels statsmodels.sandbox.regression.gmm.IV2SLS.from_formula statsmodels.sandbox.regression.gmm.IV2SLS.from\_formula
=======================================================
`classmethod IV2SLS.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)`
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
statsmodels statsmodels.discrete.discrete_model.MultinomialResults.resid_misclassified statsmodels.discrete.discrete\_model.MultinomialResults.resid\_misclassified
============================================================================
`MultinomialResults.resid_misclassified()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MultinomialResults.resid_misclassified)
Residuals indicating which observations are misclassified.
#### Notes
The residuals for the multinomial model are defined as
\[argmax(y\_i) \neq argmax(p\_i)\] where \(argmax(y\_i)\) is the index of the category for the endogenous variable and \(argmax(p\_i)\) is the index of the predicted probabilities for each category. That is, the residual is a binary indicator that is 0 if the category with the highest predicted probability is the same as that of the observed variable and 1 otherwise.
statsmodels statsmodels.tsa.arima_model.ARIMAResults.wald_test statsmodels.tsa.arima\_model.ARIMAResults.wald\_test
====================================================
`ARIMAResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)`
Compute a Wald-test for a joint linear hypothesis.
| Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) β
+ array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β Default is 1.0 for no scaling.
* **invcov** (*array-like**,* *optional*) β A q x q array to specify an inverse covariance matrix based on a restrictions matrix.
* **use\_f** (*bool*) β If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis.
|
| Returns: | **res** β The results for the test are attributes of this results instance. |
| Return type: | ContrastResults instance |
See also
[`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.tsa.arima_model.arimaresults.f_test#statsmodels.tsa.arima_model.ARIMAResults.f_test "statsmodels.tsa.arima_model.ARIMAResults.f_test"), [`t_test`](statsmodels.tsa.arima_model.arimaresults.t_test#statsmodels.tsa.arima_model.ARIMAResults.t_test "statsmodels.tsa.arima_model.ARIMAResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
#### Notes
The matrix `r_matrix` is assumed to be non-singular. More precisely,
r\_matrix (pX pX.T) r\_matrix.T
is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
| programming_docs |
statsmodels statsmodels.emplike.descriptive.DescStatUV.test_var statsmodels.emplike.descriptive.DescStatUV.test\_var
====================================================
`DescStatUV.test_var(sig2_0, return_weights=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV.test_var)
Returns -2 x log-likelihoog ratio and the p-value for the hypothesized variance
| Parameters: | * **sig2\_0** (*float*) β Hypothesized variance to be tested
* **return\_weights** (*bool*) β If True, returns the weights that maximize the likelihood of observing sig2\_0. Default is False
|
| Returns: | **test\_results** β The log-likelihood ratio and the p\_value of sig2\_0 |
| Return type: | tuple |
#### Examples
```
>>> import numpy as np
>>> import statsmodels.api as sm
>>> random_numbers = np.random.standard_normal(1000)*100
>>> el_analysis = sm.emplike.DescStat(random_numbers)
>>> hyp_test = el_analysis.test_var(9500)
```
statsmodels statsmodels.tsa.statespace.tools.diff statsmodels.tsa.statespace.tools.diff
=====================================
`statsmodels.tsa.statespace.tools.diff(series, k_diff=1, k_seasonal_diff=None, seasonal_periods=1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/tools.html#diff)
Difference a series simply and/or seasonally along the zero-th axis.
Given a series (denoted \(y\_t\)), performs the differencing operation
\[\Delta^d \Delta\_s^D y\_t\] where \(d =\) `diff`, \(s =\) `seasonal_periods`, \(D =\) `seasonal_diff`, and \(\Delta\) is the difference operator.
| Parameters: | * **series** (*array\_like*) β The series to be differenced.
* **diff** (*int**,* *optional*) β The number of simple differences to perform. Default is 1.
* **seasonal\_diff** (*int* *or* *None**,* *optional*) β The number of seasonal differences to perform. Default is no seasonal differencing.
* **seasonal\_periods** (*int**,* *optional*) β The seasonal lag. Default is 1. Unused if there is no seasonal differencing.
|
| Returns: | **differenced** β The differenced array. |
| Return type: | array |
statsmodels statsmodels.tsa.arima_process.deconvolve statsmodels.tsa.arima\_process.deconvolve
=========================================
`statsmodels.tsa.arima_process.deconvolve(num, den, n=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#deconvolve)
Deconvolves divisor out of signal, division of polynomials for n terms
calculates den^{-1} \* num
| Parameters: | * **num** (*array\_like*) β signal or lag polynomial
* **denom** (*array\_like*) β coefficients of lag polynomial (linear filter)
* **n** (*None* *or* *int*) β number of terms of quotient
|
| Returns: | * **quot** (*array*) β quotient or filtered series
* **rem** (*array*) β remainder
|
#### Notes
If num is a time series, then this applies the linear filter den^{-1}. If both num and den are both lag polynomials, then this calculates the quotient polynomial for n terms and also returns the remainder.
This is copied from scipy.signal.signaltools and added n as optional parameter.
statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.score_obs statsmodels.discrete.discrete\_model.NegativeBinomial.score\_obs
================================================================
`NegativeBinomial.score_obs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomial.score_obs)
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_partial_residuals statsmodels.genmod.generalized\_estimating\_equations.GEEResults.plot\_partial\_residuals
=========================================================================================
`GEEResults.plot_partial_residuals(focus_exog, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.plot_partial_residuals)
Create a partial residual, or βcomponent plus residualβ plot for a fited regression model.
| Parameters: | * **focus\_exog** (*int* *or* *string*) β The column index of exog, or variable name, indicating the variable whose role in the regression is to be assessed.
* **ax** (*Axes instance*) β Matplotlib Axes instance
|
| Returns: | **fig** β A matplotlib figure instance. |
| Return type: | matplotlib Figure |
statsmodels statsmodels.stats.contingency_tables.SquareTable.independence_probabilities statsmodels.stats.contingency\_tables.SquareTable.independence\_probabilities
=============================================================================
`SquareTable.independence_probabilities()`
statsmodels statsmodels.regression.linear_model.RegressionResults.resid statsmodels.regression.linear\_model.RegressionResults.resid
============================================================
`RegressionResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.resid)
statsmodels statsmodels.iolib.summary.Summary.add_table_2cols statsmodels.iolib.summary.Summary.add\_table\_2cols
===================================================
`Summary.add_table_2cols(res, title=None, gleft=None, gright=None, yname=None, xname=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary.html#Summary.add_table_2cols)
add a double table, 2 tables with one column merged horizontally
| Parameters: | * **res** (*results instance*) β some required information is directly taken from the result instance
* **title** (*string* *or* *None*) β if None, then a default title is used.
* **gleft** (*list of tuples*) β elements for the left table, tuples are (name, value) pairs If gleft is None, then a default table is created
* **gright** (*list of tuples* *or* *None*) β elements for the right table, tuples are (name, value) pairs
* **yname** (*string* *or* *None*) β optional name for the endogenous variable, default is βyβ
* **xname** (*list of strings* *or* *None*) β optional names for the exogenous variables, default is βvar\_xxβ
|
| Returns: | **None** |
| Return type: | tables are attached |
statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.score statsmodels.tsa.statespace.mlemodel.MLEModel.score
==================================================
`MLEModel.score(params, *args, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.score)
Compute the score function at params.
| Parameters: | * **params** (*array\_like*) β Array of parameters at which to evaluate the score.
* **args** β Additional positional arguments to the `loglike` method.
* **kwargs** β Additional keyword arguments to the `loglike` method.
|
| Returns: | **score** β Score, evaluated at `params`. |
| Return type: | array |
#### Notes
This is a numerical approximation, calculated using first-order complex step differentiation on the `loglike` method.
Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`).
statsmodels statsmodels.regression.linear_model.RegressionResults.mse_model statsmodels.regression.linear\_model.RegressionResults.mse\_model
=================================================================
`RegressionResults.mse_model()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.mse_model)
statsmodels statsmodels.stats.contingency_tables.Table2x2.cumulative_log_oddsratios statsmodels.stats.contingency\_tables.Table2x2.cumulative\_log\_oddsratios
==========================================================================
`Table2x2.cumulative_log_oddsratios()`
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.is_stable statsmodels.tsa.vector\_ar.var\_model.VARResults.is\_stable
===========================================================
`VARResults.is_stable(verbose=False)`
Determine stability based on model coefficients
| Parameters: | **verbose** (*bool*) β Print eigenvalues of the VAR(1) companion |
#### Notes
Checks if det(I - Az) = 0 for any mod(z) <= 1, so all the eigenvalues of the companion matrix must lie outside the unit circle
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.simulate_var statsmodels.tsa.vector\_ar.var\_model.VARResults.simulate\_var
==============================================================
`VARResults.simulate_var(steps=None, offset=None, seed=None)`
simulate the VAR(p) process for the desired number of steps
| Parameters: | * **steps** (*None* *or* *int*) β number of observations to simulate, this includes the initial observations to start the autoregressive process. If offset is not None, then exog of the model are used if they were provided in the model
* **offset** (*None* *or* *ndarray* *(**steps**,* *neqs**)*) β If not None, then offset is added as an observation specific intercept to the autoregression. If it is None and either trend (including intercept) or exog were used in the VAR model, then the linear predictor of those components will be used as offset. This should have the same number of rows as steps, and the same number of columns as endogenous variables (neqs).
* **seed** (*None* *or* *integer*) β If seed is not None, then it will be used with for the random variables generated by numpy.random.
|
| Returns: | **endog\_simulated** β Endog of the simulated VAR process |
| Return type: | nd\_array |
statsmodels statsmodels.tsa.statespace.representation.FrozenRepresentation statsmodels.tsa.statespace.representation.FrozenRepresentation
==============================================================
`class statsmodels.tsa.statespace.representation.FrozenRepresentation(model)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/representation.html#FrozenRepresentation)
Frozen Statespace Model
Takes a snapshot of a Statespace model.
| Parameters: | **model** ([Representation](statsmodels.tsa.statespace.representation.representation#statsmodels.tsa.statespace.representation.Representation "statsmodels.tsa.statespace.representation.Representation")) β A Statespace representation |
`nobs`
*int* β Number of observations.
`k_endog`
*int* β The dimension of the observation series.
`k_states`
*int* β The dimension of the unobserved state process.
`k_posdef`
*int* β The dimension of a guaranteed positive definite covariance matrix describing the shocks in the measurement equation.
`dtype`
*dtype* β Datatype of representation matrices
`prefix`
*str* β BLAS prefix of representation matrices
`shapes`
*dictionary of name:tuple* β A dictionary recording the shapes of each of the representation matrices as tuples.
`endog`
*array* β The observation vector.
`design`
*array* β The design matrix, \(Z\).
`obs_intercept`
*array* β The intercept for the observation equation, \(d\).
`obs_cov`
*array* β The covariance matrix for the observation equation \(H\).
`transition`
*array* β The transition matrix, \(T\).
`state_intercept`
*array* β The intercept for the transition equation, \(c\).
`selection`
*array* β The selection matrix, \(R\).
`state_cov`
*array* β The covariance matrix for the state equation \(Q\).
`missing`
*array of bool* β An array of the same size as `endog`, filled with boolean values that are True if the corresponding entry in `endog` is NaN and False otherwise.
`nmissing`
*array of int* β An array of size `nobs`, where the ith entry is the number (between 0 and `k_endog`) of NaNs in the ith row of the `endog` array.
`time_invariant`
*bool* β Whether or not the representation matrices are time-invariant
`initialization`
*str* β Kalman filter initialization method.
`initial_state`
*array\_like* β The state vector used to initialize the Kalamn filter.
`initial_state_cov`
*array\_like* β The state covariance matrix used to initialize the Kalamn filter.
#### Methods
| | |
| --- | --- |
| [`update_representation`](statsmodels.tsa.statespace.representation.frozenrepresentation.update_representation#statsmodels.tsa.statespace.representation.FrozenRepresentation.update_representation "statsmodels.tsa.statespace.representation.FrozenRepresentation.update_representation")(model) | |
statsmodels statsmodels.discrete.discrete_model.BinaryModel.initialize statsmodels.discrete.discrete\_model.BinaryModel.initialize
===========================================================
`BinaryModel.initialize()`
Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model.
statsmodels statsmodels.duration.hazard_regression.PHRegResults.score_residuals statsmodels.duration.hazard\_regression.PHRegResults.score\_residuals
=====================================================================
`PHRegResults.score_residuals()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.score_residuals)
A matrix containing the score residuals.
statsmodels statsmodels.sandbox.regression.try_catdata.groupstatsbin statsmodels.sandbox.regression.try\_catdata.groupstatsbin
=========================================================
`statsmodels.sandbox.regression.try_catdata.groupstatsbin(factors, values)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_catdata.html#groupstatsbin)
uses np.bincount, assumes factors/labels are integers
statsmodels statsmodels.genmod.families.family.Poisson.resid_anscombe statsmodels.genmod.families.family.Poisson.resid\_anscombe
==========================================================
`Poisson.resid_anscombe(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Poisson.resid_anscombe)
The Anscombe residuals
| Parameters: | * **endog** (*array*) β The endogenous response variable
* **mu** (*array*) β The inverse of the link function at the linear predicted values.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **scale** (*float**,* *optional*) β An optional argument to divide the residuals by sqrt(scale). The default is 1.
|
| Returns: | **resid\_anscombe** β The Anscome residuals for the Poisson family defined below |
| Return type: | array |
#### Notes
\[resid\\_anscombe\_i = (3/2) \* (endog\_i^{2/3} - \mu\_i^{2/3}) / \mu\_i^{1/6} \* \sqrt(var\\_weights)\]
statsmodels statsmodels.iolib.table.SimpleTable.count statsmodels.iolib.table.SimpleTable.count
=========================================
`SimpleTable.count(value) β integer -- return number of occurrences of value`
statsmodels statsmodels.stats.power.FTestAnovaPower.plot_power statsmodels.stats.power.FTestAnovaPower.plot\_power
===================================================
`FTestAnovaPower.plot_power(dep_var='nobs', nobs=None, effect_size=None, alpha=0.05, ax=None, title=None, plt_kwds=None, **kwds)`
plot power with number of observations or effect size on x-axis
| Parameters: | * **dep\_var** (*string in* *[**'nobs'**,* *'effect\_size'**,* *'alpha'**]*) β This specifies which variable is used for the horizontal axis. If dep\_var=βnobsβ (default), then one curve is created for each value of `effect_size`. If dep\_var=βeffect\_sizeβ or alpha, then one curve is created for each value of `nobs`.
* **nobs** (*scalar* *or* *array\_like*) β specifies the values of the number of observations in the plot
* **effect\_size** (*scalar* *or* *array\_like*) β specifies the values of the effect\_size in the plot
* **alpha** (*float* *or* *array\_like*) β The significance level (type I error) used in the power calculation. Can only be more than a scalar, if `dep_var='alpha'`
* **ax** (*None* *or* *axis instance*) β If ax is None, than a matplotlib figure is created. If ax is a matplotlib axis instance, then it is reused, and the plot elements are created with it.
* **title** (*string*) β title for the axis. Use an empty string, `''`, to avoid a title.
* **plt\_kwds** (*None* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) β not used yet
* **kwds** (*optional keywords for power function*) β These remaining keyword arguments are used as arguments to the power function. Many power function support `alternative` as a keyword argument, two-sample test support `ratio`.
|
| Returns: | **fig** |
| Return type: | matplotlib figure instance |
#### Notes
This works only for classes where the `power` method has `effect_size`, `nobs` and `alpha` as the first three arguments. If the second argument is `nobs1`, then the number of observations in the plot are those for the first sample. TODO: fix this for FTestPower and GofChisquarePower
TODO: maybe add line variable, if we want more than nobs and effectsize
statsmodels statsmodels.discrete.discrete_model.MNLogit.cdf statsmodels.discrete.discrete\_model.MNLogit.cdf
================================================
`MNLogit.cdf(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MNLogit.cdf)
Multinomial logit cumulative distribution function.
| Parameters: | **X** (*array*) β The linear predictor of the model XB. |
| Returns: | **cdf** β The cdf evaluated at `X`. |
| Return type: | ndarray |
#### Notes
In the multinomial logit model. .. math:: frac{expleft(beta\_{j}^{prime}x\_{i}right)}{sum\_{k=0}^{J}expleft(beta\_{k}^{prime}x\_{i}right)}
statsmodels statsmodels.discrete.discrete_model.MNLogit.information statsmodels.discrete.discrete\_model.MNLogit.information
========================================================
`MNLogit.information(params)`
Fisher information matrix of model
Returns -Hessian of loglike evaluated at params.
statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.logpdf statsmodels.sandbox.distributions.extras.ACSkewT\_gen.logpdf
============================================================
`ACSkewT_gen.logpdf(x, *args, **kwds)`
Log of the probability density function at x of the given RV.
This uses a more numerically accurate calculation if available.
| Parameters: | * **x** (*array\_like*) β quantiles
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
| Returns: | **logpdf** β Log of the probability density function evaluated at x |
| Return type: | array\_like |
statsmodels statsmodels.sandbox.regression.gmm.GMMResults.wald_test statsmodels.sandbox.regression.gmm.GMMResults.wald\_test
========================================================
`GMMResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)`
Compute a Wald-test for a joint linear hypothesis.
| Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) β
+ array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero.
+ str : The full hypotheses to test can be given as a string. See the examples.
+ tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector.
* **cov\_p** (*array-like**,* *optional*) β An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used.
* **scale** (*float**,* *optional*) β Default is 1.0 for no scaling.
* **invcov** (*array-like**,* *optional*) β A q x q array to specify an inverse covariance matrix based on a restrictions matrix.
* **use\_f** (*bool*) β If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis.
|
| Returns: | **res** β The results for the test are attributes of this results instance. |
| Return type: | ContrastResults instance |
See also
[`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.sandbox.regression.gmm.gmmresults.f_test#statsmodels.sandbox.regression.gmm.GMMResults.f_test "statsmodels.sandbox.regression.gmm.GMMResults.f_test"), [`t_test`](statsmodels.sandbox.regression.gmm.gmmresults.t_test#statsmodels.sandbox.regression.gmm.GMMResults.t_test "statsmodels.sandbox.regression.gmm.GMMResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
#### Notes
The matrix `r_matrix` is assumed to be non-singular. More precisely,
r\_matrix (pX pX.T) r\_matrix.T
is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
| programming_docs |
statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.from_formula statsmodels.discrete.discrete\_model.NegativeBinomial.from\_formula
===================================================================
`classmethod NegativeBinomial.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)`
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
statsmodels statsmodels.genmod.families.family.Binomial.loglike statsmodels.genmod.families.family.Binomial.loglike
===================================================
`Binomial.loglike(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)`
The log-likelihood function in terms of the fitted mean response.
| Parameters: | * **endog** (*array*) β Usually the endogenous response variable.
* **mu** (*array*) β Usually but not always the fitted mean response variable.
* **var\_weights** (*array-like*) β 1d array of variance (analytic) weights. The default is 1.
* **freq\_weights** (*array-like*) β 1d array of frequency weights. The default is 1.
* **scale** (*float*) β The scale parameter. The default is 1.
|
| Returns: | **ll** β The value of the loglikelihood evaluated at (endog, mu, var\_weights, freq\_weights, scale) as defined below. |
| Return type: | float |
#### Notes
Where \(ll\_i\) is the by-observation log-likelihood:
\[ll = \sum(ll\_i \* freq\\_weights\_i)\] `ll_i` is defined for each family. endog and mu are not restricted to `endog` and `mu` respectively. For instance, you could call both `loglike(endog, endog)` and `loglike(endog, mu)` to get the log-likelihood ratio.
statsmodels statsmodels.multivariate.multivariate_ols.MultivariateTestResults statsmodels.multivariate.multivariate\_ols.MultivariateTestResults
==================================================================
`class statsmodels.multivariate.multivariate_ols.MultivariateTestResults(mv_test_df, endog_names, exog_names)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/multivariate_ols.html#MultivariateTestResults)
Multivariate test results class Returned by `mv_test` method of `_MultivariateOLSResults` class
`results`
*dict* β
`For hypothesis name key:` results[key][βstatβ] contains the multivaraite test results results[key][βcontrast\_Lβ] contains the contrast\_L matrix results[key][βtransform\_Mβ] contains the transform\_M matrix results[key][βconstant\_Cβ] contains the constant\_C matrix
`endog_names`
*string*
`exog_names`
*string*
`summary_frame`
*multiindex dataframe* β Returns results as a multiindex dataframe
#### Methods
| | | | | |
| --- | --- | --- | --- | --- |
| [`summary`](statsmodels.multivariate.multivariate_ols.multivariatetestresults.summary#statsmodels.multivariate.multivariate_ols.MultivariateTestResults.summary "statsmodels.multivariate.multivariate_ols.MultivariateTestResults.summary")([show\_contrast\_L, show\_transform\_M, β¦]) |
| param contrast\_L: |
| | Whether to show contrast\_L matrix :type contrast\_L: True or False :param transform\_M: Whether to show transform\_M matrix :type transform\_M: True or False |
|
#### Attributes
| | |
| --- | --- |
| [`summary_frame`](#statsmodels.multivariate.multivariate_ols.MultivariateTestResults.summary_frame "statsmodels.multivariate.multivariate_ols.MultivariateTestResults.summary_frame") | Return results as a multiindex dataframe |
statsmodels statsmodels.discrete.discrete_model.MultinomialResults.aic statsmodels.discrete.discrete\_model.MultinomialResults.aic
===========================================================
`MultinomialResults.aic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MultinomialResults.aic)
statsmodels statsmodels.multivariate.cancorr.CanCorr.predict statsmodels.multivariate.cancorr.CanCorr.predict
================================================
`CanCorr.predict(params, exog=None, *args, **kwargs)`
After a model has been fit predict returns the fitted values.
This is a placeholder intended to be overwritten by individual models.
statsmodels statsmodels.tsa.holtwinters.SimpleExpSmoothing.initialize statsmodels.tsa.holtwinters.SimpleExpSmoothing.initialize
=========================================================
`SimpleExpSmoothing.initialize()`
Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed.
statsmodels statsmodels.tsa.filters.filtertools.convolution_filter statsmodels.tsa.filters.filtertools.convolution\_filter
=======================================================
`statsmodels.tsa.filters.filtertools.convolution_filter(x, filt, nsides=2)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/filters/filtertools.html#convolution_filter)
Linear filtering via convolution. Centered and backward displaced moving weighted average.
| Parameters: | * **x** (*array\_like*) β data array, 1d or 2d, if 2d then observations in rows
* **filt** (*array\_like*) β Linear filter coefficients in reverse time-order. Should have the same number of dimensions as x though if 1d and `x` is 2d will be coerced to 2d.
* **nsides** (*int**,* *optional*) β If 2, a centered moving average is computed using the filter coefficients. If 1, the filter coefficients are for past values only. Both methods use scipy.signal.convolve.
|
| Returns: | **y** β Filtered array, number of columns determined by x and filt. If a pandas object is given, a pandas object is returned. The index of the return is the exact same as the time period in `x` |
| Return type: | ndarray, 2d |
#### Notes
In nsides == 1, x is filtered
```
y[n] = filt[0]*x[n-1] + ... + filt[n_filt-1]*x[n-n_filt]
```
where n\_filt is len(filt).
If nsides == 2, x is filtered around lag 0
```
y[n] = filt[0]*x[n - n_filt/2] + ... + filt[n_filt / 2] * x[n]
+ ... + x[n + n_filt/2]
```
where n\_filt is len(filt). If n\_filt is even, then more of the filter is forward in time than backward.
If filt is 1d or (nlags,1) one lag polynomial is applied to all variables (columns of x). If filt is 2d, (nlags, nvars) each series is independently filtered with its own lag polynomial, uses loop over nvar. This is different than the usual 2d vs 2d convolution.
Filtering is done with scipy.signal.convolve, so it will be reasonably fast for medium sized data. For large data fft convolution would be faster.
statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.wald_test_terms statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.wald\_test\_terms
=======================================================================================
`ZeroInflatedNegativeBinomialResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)`
Compute a sequence of Wald tests for terms over multiple columns
This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero.
`Terms` are defined by the underlying formula or by string matching.
| Parameters: | * **skip\_single** (*boolean*) β If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included.
* **extra\_constraints** (*ndarray*) β not tested yet
* **combine\_terms** (*None* *or* *list of strings*) β Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test.
|
| Returns: | **test\_result** β The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. |
| Return type: | result instance |
#### Examples
```
>>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit()
>>> res_ols.wald_test_terms()
<class 'statsmodels.stats.contrast.WaldTestResults'>
F P>F df constraint df denom
Intercept 279.754525 2.37985521351e-22 1 51
C(Duration, Sum) 5.367071 0.0245738436636 1 51
C(Weight, Sum) 12.432445 3.99943118767e-05 2 51
C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51
```
```
>>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0')
>>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight'])
>>> print(wt)
chi2 P>chi2 df constraint
Intercept 15.695625 7.43960374424e-05 1
C(Weight) 16.132616 0.000313940174705 2
C(Duration) 1.009147 0.315107378931 1
C(Weight):C(Duration) 0.216694 0.897315972824 2
Duration 11.187849 0.010752286833 3
Weight 30.263368 4.32586407145e-06 4
```
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.maparams statsmodels.tsa.statespace.sarimax.SARIMAXResults.maparams
==========================================================
`SARIMAXResults.maparams()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults.maparams)
(array) Moving average parameters actually estimated in the model. Does not include seasonal moving average parameters (see `seasonalmaparams`) or parameters whose values are constrained to be zero.
statsmodels statsmodels.stats.outliers_influence.OLSInfluence.cov_ratio statsmodels.stats.outliers\_influence.OLSInfluence.cov\_ratio
=============================================================
`OLSInfluence.cov_ratio()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.cov_ratio)
(cached attribute) covariance ratio between LOOO and original
This uses determinant of the estimate of the parameter covariance from leave-one-out estimates. requires leave one out loop for observations
statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.moment statsmodels.sandbox.distributions.transformed.LogTransf\_gen.moment
===================================================================
`LogTransf_gen.moment(n, *args, **kwds)`
n-th order non-central moment of distribution.
| Parameters: | * **n** (*int**,* *n >= 1*) β Order of moment.
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information).
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
statsmodels statsmodels.distributions.empirical_distribution.ECDF statsmodels.distributions.empirical\_distribution.ECDF
======================================================
`class statsmodels.distributions.empirical_distribution.ECDF(x, side='right')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/distributions/empirical_distribution.html#ECDF)
Return the Empirical CDF of an array as a step function.
| Parameters: | * **x** (*array-like*) β Observations
* **side** (*{'left'**,* *'right'}**,* *optional*) β Default is βrightβ. Defines the shape of the intervals constituting the steps. βrightβ correspond to [a, b) intervals and βleftβ to (a, b].
|
| Returns: | |
| Return type: | Empirical CDF as a step function. |
#### Examples
```
>>> import numpy as np
>>> from statsmodels.distributions.empirical_distribution import ECDF
>>>
>>> ecdf = ECDF([3, 3, 1, 4])
>>>
>>> ecdf([3, 55, 0.5, 1.5])
array([ 0.75, 1. , 0. , 0.25])
```
#### Methods
statsmodels statsmodels.stats.correlation_tools.FactoredPSDMatrix.solve statsmodels.stats.correlation\_tools.FactoredPSDMatrix.solve
============================================================
`FactoredPSDMatrix.solve(rhs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/correlation_tools.html#FactoredPSDMatrix.solve)
Solve a linear system of equations with factor-structured coefficients.
| Parameters: | **rhs** (*array-like*) β A 2 dimensional array with the same number of rows as the PSD matrix represented by the class instance. |
| Returns: | * *C^{-1} \* rhs, where C is the covariance matrix represented*
* *by this class instance.*
|
#### Notes
This function exploits the factor structure for efficiency.
statsmodels statsmodels.genmod.families.family.Gamma.weights statsmodels.genmod.families.family.Gamma.weights
================================================
`Gamma.weights(mu)`
Weights for IRLS steps
| Parameters: | **mu** (*array-like*) β The transformed mean response variable in the exponential family |
| Returns: | **w** β The weights for the IRLS steps |
| Return type: | array |
#### Notes
\[w = 1 / (g'(\mu)^2 \* Var(\mu))\]
statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.remove_data statsmodels.sandbox.regression.gmm.IVGMMResults.remove\_data
============================================================
`IVGMMResults.remove_data()`
remove data arrays, all nobs arrays from result and model
This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.
Warning
Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.
Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.
The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data.
The attributes to remove are named in:
`model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name.
`result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name)
`result._data_attr_model : arrays attached to the model` instance but not to the results instance
statsmodels statsmodels.stats.moment_helpers.cum2mc statsmodels.stats.moment\_helpers.cum2mc
========================================
`statsmodels.stats.moment_helpers.cum2mc(kappa)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/moment_helpers.html#cum2mc)
convert non-central moments to cumulants recursive formula produces as many cumulants as moments
#### References
Kenneth Lange: Numerical Analysis for Statisticians, page 40 (<http://books.google.ca/books?id=gm7kwttyRT0C&pg=PA40&lpg=PA40&dq=convert+cumulants+to+moments&source=web&ots=qyIaY6oaWH&sig=cShTDWl-YrWAzV7NlcMTRQV6y0A&hl=en&sa=X&oi=book_result&resnum=1&ct=result>)
statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.transform_params statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.transform\_params
=======================================================================================
`MarkovRegression.transform_params(unconstrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/regime_switching/markov_regression.html#MarkovRegression.transform_params)
Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation
| Parameters: | **unconstrained** (*array\_like*) β Array of unconstrained parameters used by the optimizer, to be transformed. |
| Returns: | **constrained** β Array of constrained parameters which may be used in likelihood evalation. |
| Return type: | array\_like |
statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen statsmodels.sandbox.distributions.extras.NormExpan\_gen
=======================================================
`class statsmodels.sandbox.distributions.extras.NormExpan_gen(args, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/extras.html#NormExpan_gen)
Gram-Charlier Expansion of Normal distribution
class follows scipy.stats.distributions pattern but with \_\_init\_\_
#### Methods
| | |
| --- | --- |
| [`cdf`](statsmodels.sandbox.distributions.extras.normexpan_gen.cdf#statsmodels.sandbox.distributions.extras.NormExpan_gen.cdf "statsmodels.sandbox.distributions.extras.NormExpan_gen.cdf")(x, \*args, \*\*kwds) | Cumulative distribution function of the given RV. |
| [`entropy`](statsmodels.sandbox.distributions.extras.normexpan_gen.entropy#statsmodels.sandbox.distributions.extras.NormExpan_gen.entropy "statsmodels.sandbox.distributions.extras.NormExpan_gen.entropy")(\*args, \*\*kwds) | Differential entropy of the RV. |
| [`expect`](statsmodels.sandbox.distributions.extras.normexpan_gen.expect#statsmodels.sandbox.distributions.extras.NormExpan_gen.expect "statsmodels.sandbox.distributions.extras.NormExpan_gen.expect")([func, args, loc, scale, lb, ub, β¦]) | Calculate expected value of a function with respect to the distribution. |
| [`fit`](statsmodels.sandbox.distributions.extras.normexpan_gen.fit#statsmodels.sandbox.distributions.extras.NormExpan_gen.fit "statsmodels.sandbox.distributions.extras.NormExpan_gen.fit")(data, \*args, \*\*kwds) | Return MLEs for shape (if applicable), location, and scale parameters from data. |
| [`fit_loc_scale`](statsmodels.sandbox.distributions.extras.normexpan_gen.fit_loc_scale#statsmodels.sandbox.distributions.extras.NormExpan_gen.fit_loc_scale "statsmodels.sandbox.distributions.extras.NormExpan_gen.fit_loc_scale")(data, \*args) | Estimate loc and scale parameters from data using 1st and 2nd moments. |
| [`freeze`](statsmodels.sandbox.distributions.extras.normexpan_gen.freeze#statsmodels.sandbox.distributions.extras.NormExpan_gen.freeze "statsmodels.sandbox.distributions.extras.NormExpan_gen.freeze")(\*args, \*\*kwds) | Freeze the distribution for the given arguments. |
| [`interval`](statsmodels.sandbox.distributions.extras.normexpan_gen.interval#statsmodels.sandbox.distributions.extras.NormExpan_gen.interval "statsmodels.sandbox.distributions.extras.NormExpan_gen.interval")(alpha, \*args, \*\*kwds) | Confidence interval with equal areas around the median. |
| [`isf`](statsmodels.sandbox.distributions.extras.normexpan_gen.isf#statsmodels.sandbox.distributions.extras.NormExpan_gen.isf "statsmodels.sandbox.distributions.extras.NormExpan_gen.isf")(q, \*args, \*\*kwds) | Inverse survival function (inverse of `sf`) at q of the given RV. |
| [`logcdf`](statsmodels.sandbox.distributions.extras.normexpan_gen.logcdf#statsmodels.sandbox.distributions.extras.NormExpan_gen.logcdf "statsmodels.sandbox.distributions.extras.NormExpan_gen.logcdf")(x, \*args, \*\*kwds) | Log of the cumulative distribution function at x of the given RV. |
| [`logpdf`](statsmodels.sandbox.distributions.extras.normexpan_gen.logpdf#statsmodels.sandbox.distributions.extras.NormExpan_gen.logpdf "statsmodels.sandbox.distributions.extras.NormExpan_gen.logpdf")(x, \*args, \*\*kwds) | Log of the probability density function at x of the given RV. |
| [`logsf`](statsmodels.sandbox.distributions.extras.normexpan_gen.logsf#statsmodels.sandbox.distributions.extras.NormExpan_gen.logsf "statsmodels.sandbox.distributions.extras.NormExpan_gen.logsf")(x, \*args, \*\*kwds) | Log of the survival function of the given RV. |
| [`mean`](statsmodels.sandbox.distributions.extras.normexpan_gen.mean#statsmodels.sandbox.distributions.extras.NormExpan_gen.mean "statsmodels.sandbox.distributions.extras.NormExpan_gen.mean")(\*args, \*\*kwds) | Mean of the distribution. |
| [`median`](statsmodels.sandbox.distributions.extras.normexpan_gen.median#statsmodels.sandbox.distributions.extras.NormExpan_gen.median "statsmodels.sandbox.distributions.extras.NormExpan_gen.median")(\*args, \*\*kwds) | Median of the distribution. |
| [`moment`](statsmodels.sandbox.distributions.extras.normexpan_gen.moment#statsmodels.sandbox.distributions.extras.NormExpan_gen.moment "statsmodels.sandbox.distributions.extras.NormExpan_gen.moment")(n, \*args, \*\*kwds) | n-th order non-central moment of distribution. |
| [`nnlf`](statsmodels.sandbox.distributions.extras.normexpan_gen.nnlf#statsmodels.sandbox.distributions.extras.NormExpan_gen.nnlf "statsmodels.sandbox.distributions.extras.NormExpan_gen.nnlf")(theta, x) | Return negative loglikelihood function. |
| [`pdf`](statsmodels.sandbox.distributions.extras.normexpan_gen.pdf#statsmodels.sandbox.distributions.extras.NormExpan_gen.pdf "statsmodels.sandbox.distributions.extras.NormExpan_gen.pdf")(x, \*args, \*\*kwds) | Probability density function at x of the given RV. |
| [`ppf`](statsmodels.sandbox.distributions.extras.normexpan_gen.ppf#statsmodels.sandbox.distributions.extras.NormExpan_gen.ppf "statsmodels.sandbox.distributions.extras.NormExpan_gen.ppf")(q, \*args, \*\*kwds) | Percent point function (inverse of `cdf`) at q of the given RV. |
| [`rvs`](statsmodels.sandbox.distributions.extras.normexpan_gen.rvs#statsmodels.sandbox.distributions.extras.NormExpan_gen.rvs "statsmodels.sandbox.distributions.extras.NormExpan_gen.rvs")(\*args, \*\*kwds) | Random variates of given type. |
| [`sf`](statsmodels.sandbox.distributions.extras.normexpan_gen.sf#statsmodels.sandbox.distributions.extras.NormExpan_gen.sf "statsmodels.sandbox.distributions.extras.NormExpan_gen.sf")(x, \*args, \*\*kwds) | Survival function (1 - `cdf`) at x of the given RV. |
| [`stats`](statsmodels.sandbox.distributions.extras.normexpan_gen.stats#statsmodels.sandbox.distributions.extras.NormExpan_gen.stats "statsmodels.sandbox.distributions.extras.NormExpan_gen.stats")(\*args, \*\*kwds) | Some statistics of the given RV. |
| [`std`](statsmodels.sandbox.distributions.extras.normexpan_gen.std#statsmodels.sandbox.distributions.extras.NormExpan_gen.std "statsmodels.sandbox.distributions.extras.NormExpan_gen.std")(\*args, \*\*kwds) | Standard deviation of the distribution. |
| [`var`](statsmodels.sandbox.distributions.extras.normexpan_gen.var#statsmodels.sandbox.distributions.extras.NormExpan_gen.var "statsmodels.sandbox.distributions.extras.NormExpan_gen.var")(\*args, \*\*kwds) | Variance of the distribution. |
#### Attributes
| | |
| --- | --- |
| `random_state` | Get or set the RandomState object for generating random variates. |
| programming_docs |
statsmodels statsmodels.genmod.families.family.InverseGaussian.starting_mu statsmodels.genmod.families.family.InverseGaussian.starting\_mu
===============================================================
`InverseGaussian.starting_mu(y)`
Starting value for mu in the IRLS algorithm.
| Parameters: | **y** (*array*) β The untransformed response variable. |
| Returns: | **mu\_0** β The first guess on the transformed response variable. |
| Return type: | array |
#### Notes
\[\mu\_0 = (Y + \overline{Y})/2\] Only the Binomial family takes a different initial value.
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.load statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.load
============================================================================
`classmethod ZeroInflatedGeneralizedPoissonResults.load(fname)`
load a pickle, (class method)
| Parameters: | **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle. |
| Returns: | |
| Return type: | unpickled instance |
statsmodels statsmodels.genmod.families.links.inverse_squared.inverse statsmodels.genmod.families.links.inverse\_squared.inverse
==========================================================
`inverse_squared.inverse(z)`
Inverse of the power transform link function
| Parameters: | **z** (*array-like*) β Value of the transformed mean parameters at `p` |
| Returns: | **`p`** β Mean parameters |
| Return type: | array |
#### Notes
g^(-1)(z`) = `z`**(1/`power`)
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.update statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.update
===============================================================
`DynamicFactor.update(params, transformed=True, complex_step=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/dynamic_factor.html#DynamicFactor.update)
Update the parameters of the model
Updates the representation matrices to fill in the new parameter values.
| Parameters: | * **params** (*array\_like*) β Array of new parameters.
* **transformed** (*boolean**,* *optional*) β Whether or not `params` is already transformed. If set to False, `transform_params` is called. Default is True..
|
| Returns: | **params** β Array of parameters. |
| Return type: | array\_like |
#### Notes
Let `n = k_endog`, `m = k_factors`, and `p = factor_order`. Then the `params` vector has length \([n imes m] + [n] + [m^2 imes p]\). It is expanded in the following way:
* The first \(n imes m\) parameters fill out the factor loading matrix, starting from the [0,0] entry and then proceeding along rows. These parameters are not modified in `transform_params`.
* The next \(n\) parameters provide variances for the error\_cov errors in the observation equation. They fill in the diagonal of the observation covariance matrix, and are constrained to be positive by `transofrm_params`.
* The next \(m^2 imes p\) parameters are used to create the `p` coefficient matrices for the vector autoregression describing the factor transition. They are transformed in `transform_params` to enforce stationarity of the VAR(p). They are placed so as to make the transition matrix a companion matrix for the VAR. In particular, we assume that the first \(m^2\) parameters fill the first coefficient matrix (starting at [0,0] and filling along rows), the second \(m^2\) parameters fill the second matrix, etc.
statsmodels statsmodels.regression.linear_model.OLS.hessian_factor statsmodels.regression.linear\_model.OLS.hessian\_factor
========================================================
`OLS.hessian_factor(params, scale=None, observed=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#OLS.hessian_factor)
Weights for calculating Hessian
| Parameters: | * **params** (*ndarray*) β parameter at which Hessian is evaluated
* **scale** (*None* *or* *float*) β If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale.
* **observed** (*bool*) β If True, then the observed Hessian is returned. If false then the expected information matrix is returned.
|
| Returns: | **hessian\_factor** β A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` |
| Return type: | ndarray, 1d |
statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.fit statsmodels.discrete.discrete\_model.NegativeBinomial.fit
=========================================================
`NegativeBinomial.fit(start_params=None, method='bfgs', maxiter=35, full_output=1, disp=1, callback=None, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomial.fit)
Fit the model using maximum likelihood.
The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit
Fit method for likelihood based models
| Parameters: | * **start\_params** (*array-like**,* *optional*) β Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros.
* **method** (*str**,* *optional*) β The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings:
+ βnewtonβ for Newton-Raphson, βnmβ for Nelder-Mead
+ βbfgsβ for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
+ βlbfgsβ for limited-memory BFGS with optional box constraints
+ βpowellβ for modified Powellβs method
+ βcgβ for conjugate gradient
+ βncgβ for Newton-conjugate gradient
+ βbasinhoppingβ for global basin-hopping solver
+ βminimizeβ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports.
* **maxiter** (*int**,* *optional*) β The maximum number of iterations to perform.
* **full\_output** (*bool**,* *optional*) β Set to True to have all available output in the Results objectβs mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information.
* **disp** (*bool**,* *optional*) β Set to True to print convergence messages.
* **fargs** (*tuple**,* *optional*) β Extra arguments passed to the likelihood function, i.e., loglike(x,\*args)
* **callback** (*callable callback**(**xk**)**,* *optional*) β Called after each iteration, as callback(xk), where xk is the current parameter vector.
* **retall** (*bool**,* *optional*) β Set to True to return list of solutions at each iteration. Available in Results objectβs mle\_retvals attribute.
* **skip\_hessian** (*bool**,* *optional*) β If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `βnewtonβ`).
* **kwargs** (*keywords*) β All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit:
```
warn_convergence : bool, optional
If True, checks the model for the converged flag. If the
converged flag is False, a ConvergenceWarning is issued.
```
|
#### Notes
The βbasinhoppingβ solver ignores `maxiter`, `retall`, `full_output` explicit arguments.
Optional arguments for solvers (see returned Results.mle\_settings):
```
'newton'
tol : float
Relative error in params acceptable for convergence.
'nm' -- Nelder Mead
xtol : float
Relative error in params acceptable for convergence
ftol : float
Relative error in loglike(params) acceptable for
convergence
maxfun : int
Maximum number of function evaluations to make.
'bfgs'
gtol : float
Stop when norm of gradient is less than gtol.
norm : float
Order of norm (np.Inf is max, -np.Inf is min)
epsilon
If fprime is approximated, use this value for the step
size. Only relevant if LikelihoodModel.score is None.
'lbfgs'
m : int
This many terms are used for the Hessian approximation.
factr : float
A stop condition that is a variant of relative error.
pgtol : float
A stop condition that uses the projected gradient.
epsilon
If fprime is approximated, use this value for the step
size. Only relevant if LikelihoodModel.score is None.
maxfun : int
Maximum number of function evaluations to make.
bounds : sequence
(min, max) pairs for each element in x,
defining the bounds on that parameter.
Use None for one of min or max when there is no bound
in that direction.
'cg'
gtol : float
Stop when norm of gradient is less than gtol.
norm : float
Order of norm (np.Inf is max, -np.Inf is min)
epsilon : float
If fprime is approximated, use this value for the step
size. Can be scalar or vector. Only relevant if
Likelihoodmodel.score is None.
'ncg'
fhess_p : callable f'(x,*args)
Function which computes the Hessian of f times an arbitrary
vector, p. Should only be supplied if
LikelihoodModel.hessian is None.
avextol : float
Stop when the average relative error in the minimizer
falls below this amount.
epsilon : float or ndarray
If fhess is approximated, use this value for the step size.
Only relevant if Likelihoodmodel.hessian is None.
'powell'
xtol : float
Line-search error tolerance
ftol : float
Relative error in loglike(params) for acceptable for
convergence.
maxfun : int
Maximum number of function evaluations to make.
start_direc : ndarray
Initial direction set.
'basinhopping'
niter : integer
The number of basin hopping iterations.
niter_success : integer
Stop the run if the global minimum candidate remains the
same for this number of iterations.
T : float
The "temperature" parameter for the accept or reject
criterion. Higher "temperatures" mean that larger jumps
in function value will be accepted. For best results
`T` should be comparable to the separation (in function
value) between local minima.
stepsize : float
Initial step size for use in the random displacement.
interval : integer
The interval for how often to update the `stepsize`.
minimizer : dict
Extra keyword arguments to be passed to the minimizer
`scipy.optimize.minimize()`, for example 'method' - the
minimization method (e.g. 'L-BFGS-B'), or 'tol' - the
tolerance for termination. Other arguments are mapped from
explicit argument of `fit`:
- `args` <- `fargs`
- `jac` <- `score`
- `hess` <- `hess`
'minimize'
min_method : str, optional
Name of minimization method to use.
Any method specific arguments can be passed directly.
For a list of methods and their arguments, see
documentation of `scipy.optimize.minimize`.
If no method is specified, then BFGS is used.
```
statsmodels statsmodels.stats.power.TTestPower.solve_power statsmodels.stats.power.TTestPower.solve\_power
===============================================
`TTestPower.solve_power(effect_size=None, nobs=None, alpha=None, power=None, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#TTestPower.solve_power)
solve for any one parameter of the power of a one sample t-test
for the one sample t-test the keywords are: effect\_size, nobs, alpha, power Exactly one needs to be `None`, all others need numeric values.
This test can also be used for a paired t-test, where effect size is defined in terms of the mean difference, and nobs is the number of pairs.
| Parameters: | * **effect\_size** (*float*) β standardized effect size, mean divided by the standard deviation. effect size has to be positive.
* **nobs** (*int* *or* *float*) β sample size, number of observations.
* **alpha** (*float in interval* *(**0**,**1**)*) β significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true.
* **power** (*float in interval* *(**0**,**1**)*) β power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true.
* **alternative** (*string**,* *'two-sided'* *(**default**) or* *'one-sided'*) β extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. βone-sidedβ assumes we are in the relevant tail.
|
| Returns: | * **value** (*float*) β The value of the parameter that was set to None in the call. The value solves the power equation given the remaining parameters.
* *\*attaches\**
* **cache\_fit\_res** (*list*) β Cache of the result of the root finding procedure for the latest call to `solve_power`, mainly for debugging purposes. The first element is the success indicator, one if successful. The remaining elements contain the return information of the up to three solvers that have been tried.
|
#### Notes
The function uses scipy.optimize for finding the value that satisfies the power equation. It first uses `brentq` with a prior search for bounds. If this fails to find a root, `fsolve` is used. If `fsolve` also fails, then, for `alpha`, `power` and `effect_size`, `brentq` with fixed bounds is used. However, there can still be cases where this fails.
statsmodels statsmodels.discrete.discrete_model.BinaryResults.save statsmodels.discrete.discrete\_model.BinaryResults.save
=======================================================
`BinaryResults.save(fname, remove_data=False)`
save a pickle of this instance
| Parameters: | * **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle.
* **remove\_data** (*bool*) β If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None.
|
#### Notes
If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception.
statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.err_band_sz1 statsmodels.tsa.vector\_ar.irf.IRAnalysis.err\_band\_sz1
========================================================
`IRAnalysis.err_band_sz1(orth=False, svar=False, repl=1000, signif=0.05, seed=None, burn=100, component=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.err_band_sz1)
IRF Sims-Zha error band method 1. Assumes symmetric error bands around mean.
| Parameters: | * **orth** (*bool**,* *default False*) β Compute orthogonalized impulse responses
* **repl** (*int**,* *default 1000*) β Number of MC replications
* **signif** (*float* *(**0 < signif < 1**)*) β Significance level for error bars, defaults to 95% CI
* **seed** (*int**,* *default None*) β np.random seed
* **burn** (*int**,* *default 100*) β Number of initial simulated obs to discard
* **component** (*neqs x neqs array**,* *default to largest for each*) β Index of column of eigenvector/value to use for each error band Note: period of impulse (t=0) is not included when computing principle component
|
#### References
Sims, Christopher A., and Tao Zha. 1999. βError Bands for Impulse Responseβ. Econometrica 67: 1113-1155.
statsmodels statsmodels.genmod.generalized_linear_model.GLM.loglike_mu statsmodels.genmod.generalized\_linear\_model.GLM.loglike\_mu
=============================================================
`GLM.loglike_mu(mu, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.loglike_mu)
Evaluate the log-likelihood for a generalized linear model.
statsmodels statsmodels.stats.power.GofChisquarePower.solve_power statsmodels.stats.power.GofChisquarePower.solve\_power
======================================================
`GofChisquarePower.solve_power(effect_size=None, nobs=None, alpha=None, power=None, n_bins=2)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#GofChisquarePower.solve_power)
solve for any one parameter of the power of a one sample chisquare-test
for the one sample chisquare-test the keywords are: effect\_size, nobs, alpha, power Exactly one needs to be `None`, all others need numeric values.
n\_bins needs to be defined, a default=2 is used.
| Parameters: | * **effect\_size** (*float*) β standardized effect size, according to Cohenβs definition. see [`statsmodels.stats.gof.chisquare_effectsize`](statsmodels.stats.gof.chisquare_effectsize#statsmodels.stats.gof.chisquare_effectsize "statsmodels.stats.gof.chisquare_effectsize")
* **nobs** (*int* *or* *float*) β sample size, number of observations.
* **alpha** (*float in interval* *(**0**,**1**)*) β significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true.
* **power** (*float in interval* *(**0**,**1**)*) β power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true.
* **n\_bins** (*int*) β number of bins or cells in the distribution
|
| Returns: | **value** β The value of the parameter that was set to None in the call. The value solves the power equation given the remaining parameters. |
| Return type: | float |
#### Notes
The function uses scipy.optimize for finding the value that satisfies the power equation. It first uses `brentq` with a prior search for bounds. If this fails to find a root, `fsolve` is used. If `fsolve` also fails, then, for `alpha`, `power` and `effect_size`, `brentq` with fixed bounds is used. However, there can still be cases where this fails.
statsmodels statsmodels.tsa.stattools.pacf statsmodels.tsa.stattools.pacf
==============================
`statsmodels.tsa.stattools.pacf(x, nlags=40, method='ywunbiased', alpha=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#pacf)
Partial autocorrelation estimated
| Parameters: | * **x** (*1d array*) β observations of time series for which pacf is calculated
* **nlags** (*int*) β largest lag for which pacf is returned
* **method** (*{'ywunbiased'**,* *'ywmle'**,* *'ols'}*) β specifies which method for the calculations to use:
+ yw or ywunbiased : yule walker with bias correction in denominator for acovf. Default.
+ ywm or ywmle : yule walker without bias correction
+ ols - regression of time series on lags of it and on constant
+ ld or ldunbiased : Levinson-Durbin recursion with bias correction
+ ldb or ldbiased : Levinson-Durbin recursion without bias correction
* **alpha** (*float**,* *optional*) β If a number is given, the confidence intervals for the given level are returned. For instance if alpha=.05, 95 % confidence intervals are returned where the standard deviation is computed according to 1/sqrt(len(x))
|
| Returns: | * **pacf** (*1d array*) β partial autocorrelations, nlags elements, including lag zero
* **confint** (*array, optional*) β Confidence intervals for the PACF. Returned if confint is not None.
|
#### Notes
This solves yule\_walker equations or ols for each desired lag and contains currently duplicate calculations.
| programming_docs |
statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.sf statsmodels.sandbox.distributions.extras.SkewNorm\_gen.sf
=========================================================
`SkewNorm_gen.sf(x, *args, **kwds)`
Survival function (1 - `cdf`) at x of the given RV.
| Parameters: | * **x** (*array\_like*) β quantiles
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
| Returns: | **sf** β Survival function evaluated at x |
| Return type: | array\_like |
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.predict statsmodels.tsa.statespace.structural.UnobservedComponentsResults.predict
=========================================================================
`UnobservedComponentsResults.predict(start=None, end=None, dynamic=False, **kwargs)`
In-sample prediction and out-of-sample forecasting
| Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation.
* **end** (*int**,* *str**, or* *datetime**,* *optional*) β Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample.
* **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) β Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead.
* **\*\*kwargs** β Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details.
|
| Returns: | **forecast** β Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k\_endog) array. |
| Return type: | array |
statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.set_smooth_method statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.set\_smooth\_method
==============================================================================
`KalmanSmoother.set_smooth_method(smooth_method=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_smoother.html#KalmanSmoother.set_smooth_method)
Set the smoothing method
The smoothing method can be used to override the Kalman smoother approach used. By default, the Kalman smoother used depends on the Kalman filter method.
| Parameters: | * **smooth\_method** (*integer**,* *optional*) β Bitmask value to set the filter method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details.
|
#### Notes
The smoothing method is defined by a collection of boolean flags, and is internally stored as a bitmask. The methods available are:
SMOOTH\_CONVENTIONAL = 0x01 Default Kalman smoother, as presented in Durbin and Koopman, 2012 chapter 4. SMOOTH\_CLASSICAL = 0x02 Classical Kalman smoother, as presented in Anderson and Moore, 1979 or Durbin and Koopman, 2012 chapter 4.6.1. SMOOTH\_ALTERNATIVE = 0x04 Modified Bryson-Frazier Kalman smoother method; this is identical to the conventional method of Durbin and Koopman, 2012, except that an additional intermediate step is included. SMOOTH\_UNIVARIATE = 0x08 Univariate Kalman smoother, as presented in Durbin and Koopman, 2012 chapter 6, except with modified Bryson-Frazier timing. Practically speaking, these methods should all produce the same output but different computational implications, numerical stability implications, or internal timing assumptions.
Note that only the first method is available if using a Scipy version older than 0.16.
If the bitmask is set directly via the `smooth_method` argument, then the full method must be provided.
If keyword arguments are used to set individual boolean flags, then the lowercase of the method must be used as an argument name, and the value is the desired value of the boolean flag (True or False).
Note that the filter method may also be specified by directly modifying the class attributes which are defined similarly to the keyword arguments.
The default filtering method is SMOOTH\_CONVENTIONAL.
#### Examples
```
>>> mod = sm.tsa.statespace.SARIMAX(range(10))
>>> mod.smooth_method
1
>>> mod.filter_conventional
True
>>> mod.filter_univariate = True
>>> mod.smooth_method
17
>>> mod.set_smooth_method(filter_univariate=False,
filter_collapsed=True)
>>> mod.smooth_method
33
>>> mod.set_smooth_method(smooth_method=1)
>>> mod.filter_conventional
True
>>> mod.filter_univariate
False
>>> mod.filter_collapsed
False
>>> mod.filter_univariate = True
>>> mod.smooth_method
17
```
statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_gamma statsmodels.tsa.vector\_ar.vecm.VECMResults.conf\_int\_gamma
============================================================
`VECMResults.conf_int_gamma(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.conf_int_gamma)
statsmodels statsmodels.sandbox.regression.gmm.GMMResults.compare_j statsmodels.sandbox.regression.gmm.GMMResults.compare\_j
========================================================
`GMMResults.compare_j(other)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMMResults.compare_j)
overidentification test for comparing two nested gmm estimates
This assumes that some moment restrictions have been dropped in one of the GMM estimates relative to the other.
Not tested yet
We are comparing two separately estimated models, that use different weighting matrices. It is not guaranteed that the resulting difference is positive.
TODO: Check in which cases Stata programs use the same weigths
statsmodels statsmodels.discrete.discrete_model.MultinomialResults.summary statsmodels.discrete.discrete\_model.MultinomialResults.summary
===============================================================
`MultinomialResults.summary(yname=None, xname=None, title=None, alpha=0.05, yname_list=None)`
Summarize the Regression Results
| Parameters: | * **yname** (*string**,* *optional*) β Default is `y`
* **xname** (*list of strings**,* *optional*) β Default is `var_##` for ## in p the number of regressors
* **title** (*string**,* *optional*) β Title for the top table. If not None, then this replaces the default title
* **alpha** (*float*) β significance level for the confidence intervals
|
| Returns: | **smry** β this holds the summary tables and text, which can be printed or converted to various output formats. |
| Return type: | Summary instance |
See also
[`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary")
class to hold summary results
statsmodels statsmodels.graphics.gofplots.ProbPlot.probplot statsmodels.graphics.gofplots.ProbPlot.probplot
===============================================
`ProbPlot.probplot(xlabel=None, ylabel=None, line=None, exceed=False, ax=None, **plotkwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#ProbPlot.probplot)
Probability plot of the unscaled quantiles of x versus the probabilities of a distibution (not to be confused with a P-P plot).
The x-axis is scaled linearly with the quantiles, but the probabilities are used to label the axis.
| Parameters: | * **ylabel** (*xlabel**,*) β User-provided lables for the x-axis and y-axis. If None (default), other values are used depending on the status of the kwarg `other`.
* **line** (*str {'45'**,* *'s'**,* *'r'**,* *q'}* *or* *None**,* *optional*) β Options for the reference line to which the data is compared:
+ β45β - 45-degree line
+ βsβ - standardized line, the expected order statistics are scaled by the standard deviation of the given sample and have the mean added to them
+ βrβ - A regression line is fit
+ βqβ - A line is fit through the quartiles.
+ None - by default no reference line is added to the plot.
* **exceed** (*boolean**,* *optional*) β
+ If False (default) the raw sample quantiles are plotted against the theoretical quantiles, show the probability that a sample will not exceed a given value
+ If True, the theoretical quantiles are flipped such that the figure displays the probability that a sample will exceed a given value.
* **ax** (*Matplotlib AxesSubplot instance**,* *optional*) β If given, this subplot is used to plot in instead of a new figure being created.
* **\*\*plotkwargs** (*additional matplotlib arguments to be passed to the*) β `plot` command.
|
| Returns: | **fig** β If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. |
| Return type: | Matplotlib figure instance |
statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.bootstrap statsmodels.regression.mixed\_linear\_model.MixedLMResults.bootstrap
====================================================================
`MixedLMResults.bootstrap(nrep=100, method='nm', disp=0, store=1)`
simple bootstrap to get mean and variance of estimator
see notes
| Parameters: | * **nrep** (*int*) β number of bootstrap replications
* **method** (*str*) β optimization method to use
* **disp** (*bool*) β If true, then optimization prints results
* **store** (*bool*) β If true, then parameter estimates for all bootstrap iterations are attached in self.bootstrap\_results
|
| Returns: | * **mean** (*array*) β mean of parameter estimates over bootstrap replications
* **std** (*array*) β standard deviation of parameter estimates over bootstrap replications
|
#### Notes
This was mainly written to compare estimators of the standard errors of the parameter estimates. It uses independent random sampling from the original endog and exog, and therefore is only correct if observations are independently distributed.
This will be moved to apply only to models with independently distributed observations.
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.load statsmodels.regression.recursive\_ls.RecursiveLSResults.load
============================================================
`classmethod RecursiveLSResults.load(fname)`
load a pickle, (class method)
| Parameters: | **fname** (*string* *or* *filehandle*) β fname can be a string to a file path or filename, or a filehandle. |
| Returns: | |
| Return type: | unpickled instance |
statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults statsmodels.regression.mixed\_linear\_model.MixedLMResults
==========================================================
`class statsmodels.regression.mixed_linear_model.MixedLMResults(model, params, cov_params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults)
Class to contain results of fitting a linear mixed effects model.
MixedLMResults inherits from statsmodels.LikelihoodModelResults
| Parameters: | **statsmodels.LikelihoodModelResults** (*See*) β |
| Returns: | * *\*\*Attributes\*\**
* **model** (*class instance*) β Pointer to MixedLM model instance that called fit.
* **normalized\_cov\_params** (*array*) β The sampling covariance matrix of the estimates
* **fe\_params** (*array*) β The fitted fixed-effects coefficients
* **cov\_re** (*array*) β The fitted random-effects covariance matrix
* **bse\_fe** (*array*) β The standard errors of the fitted fixed effects coefficients
* **bse\_re** (*array*) β The standard errors of the fitted random effects covariance matrix and variance components. The first `k_re * (k_re + 1)` parameters are the standard errors for the lower triangle of `cov_re`, the remaining elements are the standard errors for the variance components.
|
See also
`statsmodels.LikelihoodModelResults`
#### Methods
| | |
| --- | --- |
| [`aic`](statsmodels.regression.mixed_linear_model.mixedlmresults.aic#statsmodels.regression.mixed_linear_model.MixedLMResults.aic "statsmodels.regression.mixed_linear_model.MixedLMResults.aic")() | |
| [`bic`](statsmodels.regression.mixed_linear_model.mixedlmresults.bic#statsmodels.regression.mixed_linear_model.MixedLMResults.bic "statsmodels.regression.mixed_linear_model.MixedLMResults.bic")() | |
| [`bootstrap`](statsmodels.regression.mixed_linear_model.mixedlmresults.bootstrap#statsmodels.regression.mixed_linear_model.MixedLMResults.bootstrap "statsmodels.regression.mixed_linear_model.MixedLMResults.bootstrap")([nrep, method, disp, store]) | simple bootstrap to get mean and variance of estimator |
| [`bse`](statsmodels.regression.mixed_linear_model.mixedlmresults.bse#statsmodels.regression.mixed_linear_model.MixedLMResults.bse "statsmodels.regression.mixed_linear_model.MixedLMResults.bse")() | |
| [`bse_fe`](statsmodels.regression.mixed_linear_model.mixedlmresults.bse_fe#statsmodels.regression.mixed_linear_model.MixedLMResults.bse_fe "statsmodels.regression.mixed_linear_model.MixedLMResults.bse_fe")() | Returns the standard errors of the fixed effect regression coefficients. |
| [`bse_re`](statsmodels.regression.mixed_linear_model.mixedlmresults.bse_re#statsmodels.regression.mixed_linear_model.MixedLMResults.bse_re "statsmodels.regression.mixed_linear_model.MixedLMResults.bse_re")() | Returns the standard errors of the variance parameters. |
| [`bsejac`](statsmodels.regression.mixed_linear_model.mixedlmresults.bsejac#statsmodels.regression.mixed_linear_model.MixedLMResults.bsejac "statsmodels.regression.mixed_linear_model.MixedLMResults.bsejac")() | standard deviation of parameter estimates based on covjac |
| [`bsejhj`](statsmodels.regression.mixed_linear_model.mixedlmresults.bsejhj#statsmodels.regression.mixed_linear_model.MixedLMResults.bsejhj "statsmodels.regression.mixed_linear_model.MixedLMResults.bsejhj")() | standard deviation of parameter estimates based on covHJH |
| [`conf_int`](statsmodels.regression.mixed_linear_model.mixedlmresults.conf_int#statsmodels.regression.mixed_linear_model.MixedLMResults.conf_int "statsmodels.regression.mixed_linear_model.MixedLMResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. |
| [`cov_params`](statsmodels.regression.mixed_linear_model.mixedlmresults.cov_params#statsmodels.regression.mixed_linear_model.MixedLMResults.cov_params "statsmodels.regression.mixed_linear_model.MixedLMResults.cov_params")([r\_matrix, column, scale, cov\_p, β¦]) | Returns the variance/covariance matrix. |
| [`covjac`](statsmodels.regression.mixed_linear_model.mixedlmresults.covjac#statsmodels.regression.mixed_linear_model.MixedLMResults.covjac "statsmodels.regression.mixed_linear_model.MixedLMResults.covjac")() | covariance of parameters based on outer product of jacobian of log-likelihood |
| [`covjhj`](statsmodels.regression.mixed_linear_model.mixedlmresults.covjhj#statsmodels.regression.mixed_linear_model.MixedLMResults.covjhj "statsmodels.regression.mixed_linear_model.MixedLMResults.covjhj")() | covariance of parameters based on HJJH |
| [`df_modelwc`](statsmodels.regression.mixed_linear_model.mixedlmresults.df_modelwc#statsmodels.regression.mixed_linear_model.MixedLMResults.df_modelwc "statsmodels.regression.mixed_linear_model.MixedLMResults.df_modelwc")() | |
| [`f_test`](statsmodels.regression.mixed_linear_model.mixedlmresults.f_test#statsmodels.regression.mixed_linear_model.MixedLMResults.f_test "statsmodels.regression.mixed_linear_model.MixedLMResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. |
| [`fittedvalues`](statsmodels.regression.mixed_linear_model.mixedlmresults.fittedvalues#statsmodels.regression.mixed_linear_model.MixedLMResults.fittedvalues "statsmodels.regression.mixed_linear_model.MixedLMResults.fittedvalues")() | Returns the fitted values for the model. |
| [`get_nlfun`](statsmodels.regression.mixed_linear_model.mixedlmresults.get_nlfun#statsmodels.regression.mixed_linear_model.MixedLMResults.get_nlfun "statsmodels.regression.mixed_linear_model.MixedLMResults.get_nlfun")(fun) | |
| [`hessv`](statsmodels.regression.mixed_linear_model.mixedlmresults.hessv#statsmodels.regression.mixed_linear_model.MixedLMResults.hessv "statsmodels.regression.mixed_linear_model.MixedLMResults.hessv")() | cached Hessian of log-likelihood |
| [`initialize`](statsmodels.regression.mixed_linear_model.mixedlmresults.initialize#statsmodels.regression.mixed_linear_model.MixedLMResults.initialize "statsmodels.regression.mixed_linear_model.MixedLMResults.initialize")(model, params, \*\*kwd) | |
| [`llf`](statsmodels.regression.mixed_linear_model.mixedlmresults.llf#statsmodels.regression.mixed_linear_model.MixedLMResults.llf "statsmodels.regression.mixed_linear_model.MixedLMResults.llf")() | |
| [`load`](statsmodels.regression.mixed_linear_model.mixedlmresults.load#statsmodels.regression.mixed_linear_model.MixedLMResults.load "statsmodels.regression.mixed_linear_model.MixedLMResults.load")(fname) | load a pickle, (class method) |
| [`normalized_cov_params`](statsmodels.regression.mixed_linear_model.mixedlmresults.normalized_cov_params#statsmodels.regression.mixed_linear_model.MixedLMResults.normalized_cov_params "statsmodels.regression.mixed_linear_model.MixedLMResults.normalized_cov_params")() | |
| [`predict`](statsmodels.regression.mixed_linear_model.mixedlmresults.predict#statsmodels.regression.mixed_linear_model.MixedLMResults.predict "statsmodels.regression.mixed_linear_model.MixedLMResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. |
| [`profile_re`](statsmodels.regression.mixed_linear_model.mixedlmresults.profile_re#statsmodels.regression.mixed_linear_model.MixedLMResults.profile_re "statsmodels.regression.mixed_linear_model.MixedLMResults.profile_re")(re\_ix, vtype[, num\_low, β¦]) | Profile-likelihood inference for variance parameters. |
| [`pvalues`](statsmodels.regression.mixed_linear_model.mixedlmresults.pvalues#statsmodels.regression.mixed_linear_model.MixedLMResults.pvalues "statsmodels.regression.mixed_linear_model.MixedLMResults.pvalues")() | |
| [`random_effects`](statsmodels.regression.mixed_linear_model.mixedlmresults.random_effects#statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects "statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects")() | The conditional means of random effects given the data. |
| [`random_effects_cov`](statsmodels.regression.mixed_linear_model.mixedlmresults.random_effects_cov#statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov "statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov")() | Returns the conditional covariance matrix of the random effects for each group given the data. |
| [`remove_data`](statsmodels.regression.mixed_linear_model.mixedlmresults.remove_data#statsmodels.regression.mixed_linear_model.MixedLMResults.remove_data "statsmodels.regression.mixed_linear_model.MixedLMResults.remove_data")() | remove data arrays, all nobs arrays from result and model |
| [`resid`](statsmodels.regression.mixed_linear_model.mixedlmresults.resid#statsmodels.regression.mixed_linear_model.MixedLMResults.resid "statsmodels.regression.mixed_linear_model.MixedLMResults.resid")() | Returns the residuals for the model. |
| [`save`](statsmodels.regression.mixed_linear_model.mixedlmresults.save#statsmodels.regression.mixed_linear_model.MixedLMResults.save "statsmodels.regression.mixed_linear_model.MixedLMResults.save")(fname[, remove\_data]) | save a pickle of this instance |
| [`score_obsv`](statsmodels.regression.mixed_linear_model.mixedlmresults.score_obsv#statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv "statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv")() | cached Jacobian of log-likelihood |
| [`summary`](statsmodels.regression.mixed_linear_model.mixedlmresults.summary#statsmodels.regression.mixed_linear_model.MixedLMResults.summary "statsmodels.regression.mixed_linear_model.MixedLMResults.summary")([yname, xname\_fe, xname\_re, title, β¦]) | Summarize the mixed model regression results. |
| [`t_test`](statsmodels.regression.mixed_linear_model.mixedlmresults.t_test#statsmodels.regression.mixed_linear_model.MixedLMResults.t_test "statsmodels.regression.mixed_linear_model.MixedLMResults.t_test")(r\_matrix[, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q |
| [`t_test_pairwise`](statsmodels.regression.mixed_linear_model.mixedlmresults.t_test_pairwise#statsmodels.regression.mixed_linear_model.MixedLMResults.t_test_pairwise "statsmodels.regression.mixed_linear_model.MixedLMResults.t_test_pairwise")(term\_name[, method, alpha, β¦]) | perform pairwise t\_test with multiple testing corrected p-values |
| [`tvalues`](statsmodels.regression.mixed_linear_model.mixedlmresults.tvalues#statsmodels.regression.mixed_linear_model.MixedLMResults.tvalues "statsmodels.regression.mixed_linear_model.MixedLMResults.tvalues")() | Return the t-statistic for a given parameter estimate. |
| [`wald_test`](statsmodels.regression.mixed_linear_model.mixedlmresults.wald_test#statsmodels.regression.mixed_linear_model.MixedLMResults.wald_test "statsmodels.regression.mixed_linear_model.MixedLMResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, β¦]) | Compute a Wald-test for a joint linear hypothesis. |
| [`wald_test_terms`](statsmodels.regression.mixed_linear_model.mixedlmresults.wald_test_terms#statsmodels.regression.mixed_linear_model.MixedLMResults.wald_test_terms "statsmodels.regression.mixed_linear_model.MixedLMResults.wald_test_terms")([skip\_single, β¦]) | Compute a sequence of Wald tests for terms over multiple columns |
#### Attributes
| | |
| --- | --- |
| `use_t` | |
| programming_docs |
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.loglikeobs statsmodels.tsa.statespace.structural.UnobservedComponents.loglikeobs
=====================================================================
`UnobservedComponents.loglikeobs(params, transformed=True, complex_step=False, **kwargs)`
Loglikelihood evaluation
| Parameters: | * **params** (*array\_like*) β Array of parameters at which to evaluate the loglikelihood function.
* **transformed** (*boolean**,* *optional*) β Whether or not `params` is already transformed. Default is True.
* **\*\*kwargs** β Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details.
|
#### Notes
[[1]](#id2) recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method.
#### References
| | |
| --- | --- |
| [[1]](#id1) | Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. |
See also
[`update`](statsmodels.tsa.statespace.structural.unobservedcomponents.update#statsmodels.tsa.statespace.structural.UnobservedComponents.update "statsmodels.tsa.statespace.structural.UnobservedComponents.update")
modifies the internal state of the Model to reflect new params
statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.set_inversion_method statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.set\_inversion\_method
=================================================================================
`KalmanSmoother.set_inversion_method(inversion_method=None, **kwargs)`
Set the inversion method
The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed.
| Parameters: | * **inversion\_method** (*integer**,* *optional*) β Bitmask value to set the inversion method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the inversion method by setting individual boolean flags. See notes for details.
|
#### Notes
The inversion method is defined by a collection of boolean flags, and is internally stored as a bitmask. The methods available are:
INVERT\_UNIVARIATE = 0x01 If the endogenous time series is univariate, then inversion can be performed by simple division. If this flag is set and the time series is univariate, then division will always be used even if other flags are also set. SOLVE\_LU = 0x02 Use an LU decomposition along with a linear solver (rather than ever actually inverting the matrix). INVERT\_LU = 0x04 Use an LU decomposition along with typical matrix inversion. SOLVE\_CHOLESKY = 0x08 Use a Cholesky decomposition along with a linear solver. INVERT\_CHOLESKY = 0x10 Use an Cholesky decomposition along with typical matrix inversion. If the bitmask is set directly via the `inversion_method` argument, then the full method must be provided.
If keyword arguments are used to set individual boolean flags, then the lowercase of the method must be used as an argument name, and the value is the desired value of the boolean flag (True or False).
Note that the inversion method may also be specified by directly modifying the class attributes which are defined similarly to the keyword arguments.
The default inversion method is `INVERT_UNIVARIATE | SOLVE_CHOLESKY`
Several things to keep in mind are:
* If the filtering method is specified to be univariate, then simple division is always used regardless of the dimension of the endogenous time series.
* Cholesky decomposition is about twice as fast as LU decomposition, but it requires that the matrix be positive definite. While this should generally be true, it may not be in every case.
* Using a linear solver rather than true matrix inversion is generally faster and is numerically more stable.
#### Examples
```
>>> mod = sm.tsa.statespace.SARIMAX(range(10))
>>> mod.ssm.inversion_method
1
>>> mod.ssm.solve_cholesky
True
>>> mod.ssm.invert_univariate
True
>>> mod.ssm.invert_lu
False
>>> mod.ssm.invert_univariate = False
>>> mod.ssm.inversion_method
8
>>> mod.ssm.set_inversion_method(solve_cholesky=False,
... invert_cholesky=True)
>>> mod.ssm.inversion_method
16
```
statsmodels statsmodels.regression.linear_model.GLSAR.loglike statsmodels.regression.linear\_model.GLSAR.loglike
==================================================
`GLSAR.loglike(params)`
Returns the value of the Gaussian log-likelihood function at params.
Given the whitened design matrix, the log-likelihood is evaluated at the parameter vector `params` for the dependent variable `endog`.
| Parameters: | **params** (*array-like*) β The parameter estimates |
| Returns: | **loglike** β The value of the log-likelihood function for a GLS Model. |
| Return type: | float |
#### Notes
The log-likelihood function for the normal distribution is
\[-\frac{n}{2}\log\left(\left(Y-\hat{Y}\right)^{\prime}\left(Y-\hat{Y}\right)\right)-\frac{n}{2}\left(1+\log\left(\frac{2\pi}{n}\right)\right)-\frac{1}{2}\log\left(\left|\Sigma\right|\right)\] Y and Y-hat are whitened.
statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.summary statsmodels.regression.recursive\_ls.RecursiveLSResults.summary
===============================================================
`RecursiveLSResults.summary(alpha=0.05, start=None, title=None, model_name=None, display_params=True)`
Summarize the Model
| Parameters: | * **alpha** (*float**,* *optional*) β Significance level for the confidence intervals. Default is 0.05.
* **start** (*int**,* *optional*) β Integer of the start observation. Default is 0.
* **model\_name** (*string*) β The name of the model used. Default is to use model class name.
|
| Returns: | **summary** β This holds the summary table and text, which can be printed or converted to various output formats. |
| Return type: | Summary instance |
See also
[`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary")
statsmodels statsmodels.tsa.arima_model.ARMA.loglike_css statsmodels.tsa.arima\_model.ARMA.loglike\_css
==============================================
`ARMA.loglike_css(params, set_sigma2=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA.loglike_css)
Conditional Sum of Squares likelihood function.
statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.from_formula statsmodels.miscmodels.count.PoissonZiGMLE.from\_formula
========================================================
`classmethod PoissonZiGMLE.from_formula(formula, data, subset=None, drop_cols=None, *args, **kwargs)`
Create a Model from a formula and dataframe.
| Parameters: | * **formula** (*str* *or* *generic Formula object*) β The formula specifying the model
* **data** (*array-like*) β The data for the model. See Notes.
* **subset** (*array-like*) β An array-like object of booleans, integers, or index values that indicate the subset of df to use in the model. Assumes df is a `pandas.DataFrame`
* **drop\_cols** (*array-like*) β Columns to drop from the design matrix. Cannot be used to drop terms involving categoricals.
* **args** (*extra arguments*) β These are passed to the model
* **kwargs** (*extra keyword arguments*) β These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") object or an integer indicating the depth of the namespace to use. For example, the default `eval_env=0` uses the calling namespace. If you wish to use a βcleanβ environment set `eval_env=-1`.
|
| Returns: | **model** |
| Return type: | Model instance |
#### Notes
data must define \_\_getitem\_\_ with the keys in the formula terms args and kwargs are passed on to the model instantiation. E.g., a numpy structured or rec array, a dictionary, or a pandas DataFrame.
statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.ppf statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.ppf
================================================================
`ExpTransf_gen.ppf(q, *args, **kwds)`
Percent point function (inverse of `cdf`) at q of the given RV.
| Parameters: | * **q** (*array\_like*) β lower tail probability
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
| Returns: | **x** β quantile corresponding to the lower tail probability q. |
| Return type: | array\_like |
statsmodels statsmodels.discrete.discrete_model.CountResults.prsquared statsmodels.discrete.discrete\_model.CountResults.prsquared
===========================================================
`CountResults.prsquared()`
statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.prsquared statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.prsquared
========================================================================
`GeneralizedPoissonResults.prsquared()`
statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.initialize statsmodels.tsa.statespace.varmax.VARMAXResults.initialize
==========================================================
`VARMAXResults.initialize(model, params, **kwd)`
statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.ppf statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.ppf
===========================================================
`SkewNorm2_gen.ppf(q, *args, **kwds)`
Percent point function (inverse of `cdf`) at q of the given RV.
| Parameters: | * **q** (*array\_like*) β lower tail probability
* **arg2****,** **arg3****,****..** (*arg1**,*) β The shape parameter(s) for the distribution (see docstring of the instance object for more information)
* **loc** (*array\_like**,* *optional*) β location parameter (default=0)
* **scale** (*array\_like**,* *optional*) β scale parameter (default=1)
|
| Returns: | **x** β quantile corresponding to the lower tail probability q. |
| Return type: | array\_like |
statsmodels statsmodels.regression.linear_model.RegressionResults.f_pvalue statsmodels.regression.linear\_model.RegressionResults.f\_pvalue
================================================================
`RegressionResults.f_pvalue()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.f_pvalue)
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.cov_params_opg statsmodels.tsa.statespace.mlemodel.MLEResults.cov\_params\_opg
===============================================================
`MLEResults.cov_params_opg()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.cov_params_opg)
(array) The variance / covariance matrix. Computed using the outer product of gradients method.
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoisson.score_obs statsmodels.discrete.count\_model.ZeroInflatedPoisson.score\_obs
================================================================
`ZeroInflatedPoisson.score_obs(params)`
Generic Zero Inflated model score (gradient) vector of the log-likelihood
| Parameters: | **params** (*array-like*) β The parameters of the model |
| Returns: | **score** β The score vector of the model, i.e. the first derivative of the loglikelihood function, evaluated at `params` |
| Return type: | ndarray, 1-D |
statsmodels statsmodels.iolib.summary.Summary.as_text statsmodels.iolib.summary.Summary.as\_text
==========================================
`Summary.as_text()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary.html#Summary.as_text)
return tables as string
| Returns: | **txt** β summary tables and extra text as one string |
| Return type: | string |
statsmodels statsmodels.tsa.statespace.varmax.VARMAX.set_filter_method statsmodels.tsa.statespace.varmax.VARMAX.set\_filter\_method
============================================================
`VARMAX.set_filter_method(filter_method=None, **kwargs)`
Set the filtering method
The filtering method controls aspects of which Kalman filtering approach will be used.
| Parameters: | * **filter\_method** (*integer**,* *optional*) β Bitmask value to set the filter method to. See notes for details.
* **\*\*kwargs** β Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details.
|
#### Notes
This method is rarely used. See the corresponding function in the `KalmanFilter` class for details.
statsmodels statsmodels.tsa.vector_ar.dynamic.DynamicVAR.coefs statsmodels.tsa.vector\_ar.dynamic.DynamicVAR.coefs
===================================================
`DynamicVAR.coefs()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/dynamic.html#DynamicVAR.coefs)
Return dynamic regression coefficients as Panel
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.summary statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.summary
===============================================================================
`ZeroInflatedGeneralizedPoissonResults.summary(yname=None, xname=None, title=None, alpha=0.05, yname_list=None)`
Summarize the Regression Results
| Parameters: | * **yname** (*string**,* *optional*) β Default is `y`
* **xname** (*list of strings**,* *optional*) β Default is `var_##` for ## in p the number of regressors
* **title** (*string**,* *optional*) β Title for the top table. If not None, then this replaces the default title
* **alpha** (*float*) β significance level for the confidence intervals
|
| Returns: | **smry** β this holds the summary tables and text, which can be printed or converted to various output formats. |
| Return type: | Summary instance |
See also
[`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary")
class to hold summary results
statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen statsmodels.sandbox.distributions.transformed.ExpTransf\_gen
============================================================
`class statsmodels.sandbox.distributions.transformed.ExpTransf_gen(kls, *args, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/transformed.html#ExpTransf_gen)
Distribution based on log/exp transformation
the constructor can be called with a distribution class and generates the distribution of the transformed random variable
#### Methods
| | |
| --- | --- |
| [`cdf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.cdf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.cdf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.cdf")(x, \*args, \*\*kwds) | Cumulative distribution function of the given RV. |
| [`entropy`](statsmodels.sandbox.distributions.transformed.exptransf_gen.entropy#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.entropy "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.entropy")(\*args, \*\*kwds) | Differential entropy of the RV. |
| [`expect`](statsmodels.sandbox.distributions.transformed.exptransf_gen.expect#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.expect "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.expect")([func, args, loc, scale, lb, ub, β¦]) | Calculate expected value of a function with respect to the distribution. |
| [`fit`](statsmodels.sandbox.distributions.transformed.exptransf_gen.fit#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.fit "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.fit")(data, \*args, \*\*kwds) | Return MLEs for shape (if applicable), location, and scale parameters from data. |
| [`fit_loc_scale`](statsmodels.sandbox.distributions.transformed.exptransf_gen.fit_loc_scale#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.fit_loc_scale "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.fit_loc_scale")(data, \*args) | Estimate loc and scale parameters from data using 1st and 2nd moments. |
| [`freeze`](statsmodels.sandbox.distributions.transformed.exptransf_gen.freeze#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.freeze "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.freeze")(\*args, \*\*kwds) | Freeze the distribution for the given arguments. |
| [`interval`](statsmodels.sandbox.distributions.transformed.exptransf_gen.interval#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.interval "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.interval")(alpha, \*args, \*\*kwds) | Confidence interval with equal areas around the median. |
| [`isf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.isf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.isf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.isf")(q, \*args, \*\*kwds) | Inverse survival function (inverse of `sf`) at q of the given RV. |
| [`logcdf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.logcdf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logcdf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logcdf")(x, \*args, \*\*kwds) | Log of the cumulative distribution function at x of the given RV. |
| [`logpdf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.logpdf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logpdf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logpdf")(x, \*args, \*\*kwds) | Log of the probability density function at x of the given RV. |
| [`logsf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.logsf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logsf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logsf")(x, \*args, \*\*kwds) | Log of the survival function of the given RV. |
| [`mean`](statsmodels.sandbox.distributions.transformed.exptransf_gen.mean#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.mean "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.mean")(\*args, \*\*kwds) | Mean of the distribution. |
| [`median`](statsmodels.sandbox.distributions.transformed.exptransf_gen.median#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.median "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.median")(\*args, \*\*kwds) | Median of the distribution. |
| [`moment`](statsmodels.sandbox.distributions.transformed.exptransf_gen.moment#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.moment "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.moment")(n, \*args, \*\*kwds) | n-th order non-central moment of distribution. |
| [`nnlf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.nnlf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.nnlf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.nnlf")(theta, x) | Return negative loglikelihood function. |
| [`pdf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.pdf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.pdf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.pdf")(x, \*args, \*\*kwds) | Probability density function at x of the given RV. |
| [`ppf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.ppf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.ppf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.ppf")(q, \*args, \*\*kwds) | Percent point function (inverse of `cdf`) at q of the given RV. |
| [`rvs`](statsmodels.sandbox.distributions.transformed.exptransf_gen.rvs#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.rvs "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.rvs")(\*args, \*\*kwds) | Random variates of given type. |
| [`sf`](statsmodels.sandbox.distributions.transformed.exptransf_gen.sf#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.sf "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.sf")(x, \*args, \*\*kwds) | Survival function (1 - `cdf`) at x of the given RV. |
| [`stats`](statsmodels.sandbox.distributions.transformed.exptransf_gen.stats#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.stats "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.stats")(\*args, \*\*kwds) | Some statistics of the given RV. |
| [`std`](statsmodels.sandbox.distributions.transformed.exptransf_gen.std#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.std "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.std")(\*args, \*\*kwds) | Standard deviation of the distribution. |
| [`var`](statsmodels.sandbox.distributions.transformed.exptransf_gen.var#statsmodels.sandbox.distributions.transformed.ExpTransf_gen.var "statsmodels.sandbox.distributions.transformed.ExpTransf_gen.var")(\*args, \*\*kwds) | Variance of the distribution. |
#### Attributes
| | |
| --- | --- |
| `random_state` | Get or set the RandomState object for generating random variates. |
| programming_docs |
statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.initialize_known statsmodels.tsa.statespace.mlemodel.MLEModel.initialize\_known
==============================================================
`MLEModel.initialize_known(initial_state, initial_state_cov)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.initialize_known)
statsmodels statsmodels.stats.proportion.proportions_ztost statsmodels.stats.proportion.proportions\_ztost
===============================================
`statsmodels.stats.proportion.proportions_ztost(count, nobs, low, upp, prop_var='sample')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#proportions_ztost)
Equivalence test based on normal distribution
| Parameters: | * **count** (*integer* *or* *array\_like*) β the number of successes in nobs trials. If this is array\_like, then the assumption is that this represents the number of successes for each independent sample
* **nobs** (*integer*) β the number of trials or observations, with the same length as count.
* **upp** (*low**,*) β equivalence interval low < prop1 - prop2 < upp
* **prop\_var** (*string* *or* *float in* *(**0**,* *1**)*) β prop\_var determines which proportion is used for the calculation of the standard deviation of the proportion estimate The available options for string are βsampleβ (default), βnullβ and βlimitsβ. If prop\_var is a float, then it is used directly.
|
| Returns: | * **pvalue** (*float*) β pvalue of the non-equivalence test
* **t1, pv1** (*tuple of floats*) β test statistic and pvalue for lower threshold test
* **t2, pv2** (*tuple of floats*) β test statistic and pvalue for upper threshold test
|
#### Notes
checked only for 1 sample case
statsmodels statsmodels.regression.linear_model.RegressionResults.initialize statsmodels.regression.linear\_model.RegressionResults.initialize
=================================================================
`RegressionResults.initialize(model, params, **kwd)`
statsmodels statsmodels.genmod.families.links.probit.inverse_deriv statsmodels.genmod.families.links.probit.inverse\_deriv
=======================================================
`probit.inverse_deriv(z)`
Derivative of the inverse of the CDF transformation link function
| Parameters: | **z** (*array*) β The inverse of the link function at `p` |
| Returns: | **g^(-1)β(z)** β The value of the derivative of the inverse of the logit function |
| Return type: | array |
statsmodels statsmodels.tsa.arima_model.ARMAResults.plot_predict statsmodels.tsa.arima\_model.ARMAResults.plot\_predict
======================================================
`ARMAResults.plot_predict(start=None, end=None, exog=None, dynamic=False, alpha=0.05, plot_insample=True, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.plot_predict)
Plot forecasts
| Parameters: | * **start** (*int**,* *str**, or* *datetime*) β Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type.
* **end** (*int**,* *str**, or* *datetime*) β Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction.
* **exog** (*array-like**,* *optional*) β If the model is an ARMAX and out-of-sample forecasting is requested, exog must be given. Note that youβll need to pass `k_ar` additional lags for any exogenous variables. E.g., if you fit an ARMAX(2, q) model and want to predict 5 steps, you need 7 observations to do this.
* **dynamic** (*bool**,* *optional*) β The `dynamic` keyword affects in-sample prediction. If dynamic is False, then the in-sample lagged values are used for prediction. If `dynamic` is True, then in-sample forecasts are used in place of lagged dependent variables. The first forecasted value is `start`.
* **alpha** (*float**,* *optional*) β The confidence intervals for the forecasts are (1 - alpha)%
* **plot\_insample** (*bool**,* *optional*) β Whether to plot the in-sample series. Default is True.
* **ax** (*matplotlib.Axes**,* *optional*) β Existing axes to plot with.
|
| Returns: | **fig** β The plotted Figure instance |
| Return type: | matplotlib.Figure |
#### Examples
```
>>> import statsmodels.api as sm
>>> import matplotlib.pyplot as plt
>>> import pandas as pd
>>>
>>> dta = sm.datasets.sunspots.load_pandas().data[['SUNACTIVITY']]
>>> dta.index = pd.DatetimeIndex(start='1700', end='2009', freq='A')
>>> res = sm.tsa.ARMA(dta, (3, 0)).fit()
>>> fig, ax = plt.subplots()
>>> ax = dta.loc['1950':].plot(ax=ax)
>>> fig = res.plot_predict('1990', '2012', dynamic=True, ax=ax,
... plot_insample=False)
>>> plt.show()
```
([Source code](../plots/arma_predict_plot.py), [png](../plots/arma_predict_plot.png), [hires.png](../plots/arma_predict_plot.hires.png), [pdf](../plots/arma_predict_plot.pdf))
#### Notes
It is recommended to use dates with the time-series models, as the below will probably make clear. However, if ARIMA is used without dates and/or `start` and `end` are given as indices, then these indices are in terms of the *original*, undifferenced series. Ie., given some undifferenced observations:
```
1970Q1, 1
1970Q2, 1.5
1970Q3, 1.25
1970Q4, 2.25
1971Q1, 1.2
1971Q2, 4.1
```
1970Q1 is observation 0 in the original series. However, if we fit an ARIMA(p,1,q) model then we lose this first observation through differencing. Therefore, the first observation we can forecast (if using exact MLE) is index 1. In the differenced series this is index 0, but we refer to it as 1 from the original series.
statsmodels statsmodels.discrete.discrete_model.MNLogit.fit_regularized statsmodels.discrete.discrete\_model.MNLogit.fit\_regularized
=============================================================
`MNLogit.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)`
Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method.
| Parameters: | * **start\_params** (*array-like**,* *optional*) β Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros.
* **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) β See notes for details.
* **maxiter** (*Integer* *or* *'defined\_by\_method'*) β Maximum number of iterations to perform. If βdefined\_by\_methodβ, then use method defaults (see notes).
* **full\_output** (*bool*) β Set to True to have all available output in the Results objectβs mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information.
* **disp** (*bool*) β Set to True to print convergence messages.
* **fargs** (*tuple*) β Extra arguments passed to the likelihood function, i.e., loglike(x,\*args)
* **callback** (*callable callback**(**xk**)*) β Called after each iteration, as callback(xk), where xk is the current parameter vector.
* **retall** (*bool*) β Set to True to return list of solutions at each iteration. Available in Results objectβs mle\_retvals attribute.
* **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) β The weight multiplying the l1 penalty term
* **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) β If not βoffβ, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If βautoβ, trim params using the Theory above. If βsizeβ, trim params if they have very small absolute value
* **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) β For use when trim\_mode == βsizeβ
* **auto\_trim\_tol** (*float*) β For sue when trim\_mode == βautoβ. Use
* **qc\_tol** (*float*) β Print warning and donβt allow auto trim when (ii) (above) is violated by this much.
* **qc\_verbose** (*Boolean*) β If true, print out a full QC report upon failure
|
#### Notes
Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`.
Optional arguments for the solvers (available in Results.mle\_settings):
```
'l1'
acc : float (default 1e-6)
Requested accuracy as used by slsqp
'l1_cvxopt_cp'
abstol : float
absolute accuracy (default: 1e-7).
reltol : float
relative accuracy (default: 1e-6).
feastol : float
tolerance for feasibility conditions (default: 1e-7).
refinement : int
number of iterative refinement steps when solving KKT
equations (default: 1).
```
Optimization methodology
With \(L\) the negative log likelihood, we solve the convex but non-smooth problem
\[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the βadded variablesβ \(u\_k\))
\[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to
\[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds:
1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\)
2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\)
statsmodels statsmodels.emplike.descriptive.DescStatUV.ci_kurt statsmodels.emplike.descriptive.DescStatUV.ci\_kurt
===================================================
`DescStatUV.ci_kurt(sig=0.05, upper_bound=None, lower_bound=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV.ci_kurt)
Returns the confidence interval for kurtosis.
| Parameters: | * **sig** (*float*) β The significance level. Default is .05
* **upper\_bound** (*float*) β Maximum value of kurtosis the upper limit can be. Default is .99 confidence limit assuming normality.
* **lower\_bound** (*float*) β Minimum value of kurtosis the lower limit can be. Default is .99 confidence limit assuming normality.
|
| Returns: | **Interval** β Lower and upper confidence limit |
| Return type: | tuple |
#### Notes
For small n, upper\_bound and lower\_bound may have to be provided by the user. Consider using test\_kurt to find values close to the desired significance level.
If function returns f(a) and f(b) must have different signs, consider expanding the bounds.
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald_test_terms statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald\_test\_terms
===================================================================
`SARIMAXResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)`
Compute a sequence of Wald tests for terms over multiple columns
This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero.
`Terms` are defined by the underlying formula or by string matching.
| Parameters: | * **skip\_single** (*boolean*) β If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included.
* **extra\_constraints** (*ndarray*) β not tested yet
* **combine\_terms** (*None* *or* *list of strings*) β Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test.
|
| Returns: | **test\_result** β The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. |
| Return type: | result instance |
#### Examples
```
>>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit()
>>> res_ols.wald_test_terms()
<class 'statsmodels.stats.contrast.WaldTestResults'>
F P>F df constraint df denom
Intercept 279.754525 2.37985521351e-22 1 51
C(Duration, Sum) 5.367071 0.0245738436636 1 51
C(Weight, Sum) 12.432445 3.99943118767e-05 2 51
C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51
```
```
>>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0')
>>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight'])
>>> print(wt)
chi2 P>chi2 df constraint
Intercept 15.695625 7.43960374424e-05 1
C(Weight) 16.132616 0.000313940174705 2
C(Duration) 1.009147 0.315107378931 1
C(Weight):C(Duration) 0.216694 0.897315972824 2
Duration 11.187849 0.010752286833 3
Weight 30.263368 4.32586407145e-06 4
```
statsmodels statsmodels.regression.linear_model.OLSResults.t_test_pairwise statsmodels.regression.linear\_model.OLSResults.t\_test\_pairwise
=================================================================
`OLSResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)`
perform pairwise t\_test with multiple testing corrected p-values
This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect.
| Parameters: | * **result** (*result instance*) β The results of an estimated model with a categorical main effect.
* **term\_name** (*str*) β name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names.
* **method** (*str* *or* *list of strings*) β multiple testing p-value correction, default is βhsβ, see stats.multipletesting
* **alpha** (*float*) β significance level for multiple testing reject decision.
* **factor\_labels** (*None**,* *list of str*) β Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used.
|
| Returns: | **results** β The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values.
* contrasts : matrix of constraints of the null hypothesis in the t\_test.
|
| Return type: | instance of a simple Results class |
#### Notes
Status: experimental. Currently only checked for treatment coding with and without specified reference level.
Currently there are no multiple testing corrected confidence intervals available.
#### Examples
```
>>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit()
>>> pw = res.t_test_pairwise("C(Weight)")
>>> pw.result_frame
coef std err t P>|t| Conf. Int. Low
2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563
3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803
3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488
Conf. Int. Upp. pvalue-hs reject-hs
2-1 1.093067 0.010212 True
3-1 1.763307 0.000002 True
3-2 1.130992 0.010212 True
```
statsmodels statsmodels.sandbox.distributions.transformed.negsquarenormalg statsmodels.sandbox.distributions.transformed.negsquarenormalg
==============================================================
`statsmodels.sandbox.distributions.transformed.negsquarenormalg = <statsmodels.sandbox.distributions.transformed.TransfTwo_gen object>`
Distribution based on a non-monotonic (u- or hump-shaped transformation)
the constructor can be called with a distribution class, and functions that define the non-linear transformation. and generates the distribution of the transformed random variable
Note: the transformation, itβs inverse and derivatives need to be fully specified: func, funcinvplus, funcinvminus, derivplus, derivminus. Currently no numerical derivatives or inverse are calculated
This can be used to generate distribution instances similar to the distributions in scipy.stats.
statsmodels statsmodels.stats.diagnostic.het_breuschpagan statsmodels.stats.diagnostic.het\_breuschpagan
==============================================
`statsmodels.stats.diagnostic.het_breuschpagan(resid, exog_het)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#het_breuschpagan)
Breusch-Pagan Lagrange Multiplier test for heteroscedasticity
The tests the hypothesis that the residual variance does not depend on the variables in x in the form
| Math: | sigma\_i = sigma \* f(alpha\_0 + alpha z\_i) |
Homoscedasticity implies that $alpha=0$
| Parameters: | * **resid** (*array-like*) β For the Breusch-Pagan test, this should be the residual of a regression. If an array is given in exog, then the residuals are calculated by the an OLS regression or resid on exog. In this case resid should contain the dependent variable. Exog can be the same as x. TODO: I dropped the exog option, should I add it back?
* **exog\_het** (*array\_like*) β This contains variables that might create data dependent heteroscedasticity.
|
| Returns: | * **lm** (*float*) β lagrange multiplier statistic
* **lm\_pvalue** (*float*) β p-value of lagrange multiplier test
* **fvalue** (*float*) β f-statistic of the hypothesis that the error variance does not depend on x
* **f\_pvalue** (*float*) β p-value for the f-statistic
|
#### Notes
Assumes x contains constant (for counting dof and calculation of R^2). In the general description of LM test, Greene mentions that this test exaggerates the significance of results in small or moderately large samples. In this case the F-statistic is preferrable.
*Verification*
Chisquare test statistic is exactly (<1e-13) the same result as bptest in R-stats with defaults (studentize=True).
Implementation This is calculated using the generic formula for LM test using $R^2$ (Greene, section 17.6) and not with the explicit formula (Greene, section 11.4.3). The degrees of freedom for the p-value assume x is full rank.
#### References
<http://en.wikipedia.org/wiki/Breusch%E2%80%93Pagan_test> Greene 5th edition Breusch, Pagan article
statsmodels statsmodels.discrete.discrete_model.Logit.hessian statsmodels.discrete.discrete\_model.Logit.hessian
==================================================
`Logit.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Logit.hessian)
Logit model Hessian matrix of the log-likelihood
| Parameters: | **params** (*array-like*) β The parameters of the model |
| Returns: | **hess** β The Hessian, second derivative of loglikelihood function, evaluated at `params` |
| Return type: | ndarray, (k\_vars, k\_vars) |
#### Notes
\[\frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\sum\_{i}\Lambda\_{i}\left(1-\Lambda\_{i}\right)x\_{i}x\_{i}^{\prime}\]
statsmodels statsmodels.tsa.holtwinters.ExponentialSmoothing.loglike statsmodels.tsa.holtwinters.ExponentialSmoothing.loglike
========================================================
`ExponentialSmoothing.loglike(params)`
Log-likelihood of model.
statsmodels statsmodels.sandbox.stats.multicomp.MultiComparison.kruskal statsmodels.sandbox.stats.multicomp.MultiComparison.kruskal
===========================================================
`MultiComparison.kruskal(pairs=None, multimethod='T')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#MultiComparison.kruskal)
pairwise comparison for kruskal-wallis test
This is just a reimplementation of scipy.stats.kruskal and does not yet use a multiple comparison correction.
| programming_docs |
Subsets and Splits