Exploring JavaScript >

API flashcards

Toggle expanded  |  Shuffle  | 

Categories (all | none):

Number of cards:

(Ad, please don’t block.)
Number.EPSILON()

Number.EPSILON [ES6]

The difference between 1 and the next representable floating point number. In general, a machine epsilon provides an upper bound for rounding errors in floating point arithmetic.


View API entry online
Number.MAX_VALUE()

Number.MAX_VALUE [ES1]

The largest positive finite JavaScript number.


View API entry online
Number.MIN_VALUE()

Number.MIN_VALUE [ES1]

The smallest positive JavaScript number. Approximately 5 × 10−324.


View API entry online
Number.NaN()

Number.NaN [ES1]

The same as the global variable NaN.


View API entry online
Number.NEGATIVE_INFINITY()

Number.NEGATIVE_INFINITY [ES1]

The same as -Number.POSITIVE_INFINITY.


View API entry online
Number.POSITIVE_INFINITY()

Number.POSITIVE_INFINITY [ES1]

The same as the global variable Infinity.


View API entry online
Number.isFinite()

Number.isFinite(num) [ES6]

Returns true if num is an actual number (neither Infinity nor -Infinity nor NaN).

> Number.isFinite(Infinity)
false
> Number.isFinite(-Infinity)
false
> Number.isFinite(NaN)
false
> Number.isFinite(123)
true

View API entry online
Number.isNaN()

Number.isNaN(num) [ES6]

Returns true if num is the value NaN:

> Number.isNaN(NaN)
true
> Number.isNaN(123)
false
> Number.isNaN('abc')
false

View API entry online
Number.parseFloat()

Number.parseFloat(str) [ES6]

Coerces its parameter to string and parses it as a floating point number. It ignores leading whitespace and illegal trailing characters:

> Number.parseFloat('\t 123.4#')
123.4

That can hide problems. Thus, for converting strings to numbers, Number() is usually a better choice because it only ignores leading and trailing whitespace:

> Number('\t 123.4#')
NaN

View API entry online
Number.prototype.toExponential()

Number.prototype.toExponential(fractionDigits?) [ES3]

Example: number too small to get a positive exponent via .toString().

> 1234..toString()
'1234'

> 1234..toExponential() // 3 fraction digits
'1.234e+3'
> 1234..toExponential(5)
'1.23400e+3'
> 1234..toExponential(1)
'1.2e+3'

Example: fraction not small enough to get a negative exponent via .toString().

> 0.003.toString()
'0.003'
> 0.003.toExponential()
'3e-3'

View API entry online
Number.prototype.toFixed()

Number.prototype.toFixed(fractionDigits=0) [ES3]

Returns an exponent-free string representation of the number, rounded to fractionDigits digits.

> 0.00000012.toString() // with exponent
'1.2e-7'

> 0.00000012.toFixed(10) // no exponent
'0.0000001200'
> 0.00000012.toFixed()
'0'

If the number is 1021 or greater, even .toFixed() uses an exponent:

> (10 ** 21).toFixed()
'1e+21'

View API entry online
Number.prototype.toPrecision()

Number.prototype.toPrecision(precision?) [ES3]

> 1234..toPrecision(3)  // requires exponential notation
'1.23e+3'

> 1234..toPrecision(4)
'1234'

> 1234..toPrecision(5)
'1234.0'

> 1.234.toPrecision(3)
'1.23'

View API entry online
Number.prototype.toString()

Number.prototype.toString(radix=10) [ES1]

Returns a string representation of the number.

By default, we get a base 10 numeral as a result:

> 123.456.toString()
'123.456'

If we want the numeral to have a different base, we can specify it via radix:

> 4..toString(2) // binary (base 2)
'100'
> 4.5.toString(2)
'100.1'

> 255..toString(16) // hexadecimal (base 16)
'ff'
> 255.66796875.toString(16)
'ff.ab'

> 1234567890..toString(36)
'kf12oi'

Number.parseInt() provides the inverse operation: it converts a string that contains an integer (no fraction!) numeral with a given base, to a number.

> Number.parseInt('kf12oi', 36)
1234567890

View API entry online
Number.MIN_SAFE_INTEGER()

Number.MIN_SAFE_INTEGER [ES6]

The smallest integer that JavaScript can represent unambiguously (−253+1).


View API entry online
Number.MAX_SAFE_INTEGER()

Number.MAX_SAFE_INTEGER [ES6]

The largest integer that JavaScript can represent unambiguously (253−1).


View API entry online
Number.isInteger()

Number.isInteger(num) [ES6]

Returns true if num is a number and does not have a decimal fraction.

> Number.isInteger(-17)
true
> Number.isInteger(33)
true
> Number.isInteger(33.1)
false
> Number.isInteger('33')
false
> Number.isInteger(NaN)
false
> Number.isInteger(Infinity)
false

View API entry online
Number.isSafeInteger()

Number.isSafeInteger(num) [ES6]

Returns true if num is a number and unambiguously represents an integer.


View API entry online
Number.parseInt()

Number.parseInt(str, radix=10) [ES6]

Coerces its parameter to string and parses it as an integer, ignoring leading whitespace and illegal trailing characters:

> Number.parseInt('  123#')
123

The parameter radix specifies the base of the number to be parsed:

> Number.parseInt('101', 2)
5
> Number.parseInt('FF', 16)
255

Do not use this method to convert numbers to integers: coercing to string is inefficient. And stopping before the first non-digit is not a good algorithm for removing the fraction of a number. Here is an example where it goes wrong:

> Number.parseInt(1e21, 10) // wrong
1

It is better to use one of the rounding functions of Math to convert a number to an integer:

> Math.trunc(1e21) // correct
1e+21

View API entry online
Math.E()

Math.E: number [ES1]

Euler’s number, base of the natural logarithms, approximately 2.7182818284590452354.


View API entry online
Math.LN10()

Math.LN10: number [ES1]

The natural logarithm of 10, approximately 2.302585092994046.


View API entry online
Math.LN2()

Math.LN2: number [ES1]

The natural logarithm of 2, approximately 0.6931471805599453.


View API entry online
Math.LOG10E()

Math.LOG10E: number [ES1]

The logarithm of e to base 10, approximately 0.4342944819032518.


View API entry online
Math.LOG2E()

Math.LOG2E: number [ES1]

The logarithm of e to base 2, approximately 1.4426950408889634.


View API entry online
Math.PI()

Math.PI: number [ES1]

The mathematical constant π, ratio of a circle’s circumference to its diameter, approximately 3.1415926535897932.


View API entry online
Math.SQRT1_2()

Math.SQRT1_2: number [ES1]

The square root of 1/2, approximately 0.7071067811865476.


View API entry online
Math.SQRT2()

Math.SQRT2: number [ES1]

The square root of 2, approximately 1.4142135623730951.


View API entry online
Math.cbrt()

Math.cbrt(x: number): number [ES6]

Returns the cube root of x.

> Math.cbrt(8)
2

View API entry online
Math.exp()

Math.exp(x: number): number [ES1]

Returns ex (e being Euler’s number). The inverse of Math.log().

> Math.exp(0)
1
> Math.exp(1) === Math.E
true

View API entry online
Math.expm1()

Math.expm1(x: number): number [ES6]

Returns Math.exp(x)-1. The inverse of Math.log1p(). Very small numbers (fractions close to 0) are represented with a higher precision. Therefore, this function returns more precise values whenever .exp() returns values close to 1.


View API entry online
Math.log()

Math.log(x: number): number [ES1]

Returns the natural logarithm of x (to base e, Euler’s number). The inverse of Math.exp().

> Math.log(1)
0
> Math.log(Math.E)
1
> Math.log(Math.E ** 2)
2

View API entry online
Math.log1p()

Math.log1p(x: number): number [ES6]

Returns Math.log(1 + x). The inverse of Math.expm1(). Very small numbers (fractions close to 0) are represented with a higher precision. Therefore, you can provide this function with a more precise argument whenever the argument for .log() is close to 1.


View API entry online
Math.log10()

Math.log10(x: number): number [ES6]

Returns the logarithm of x to base 10. The inverse of 10 ** x.

> Math.log10(1)
0
> Math.log10(10)
1
> Math.log10(100)
2

View API entry online
Math.log2()

Math.log2(x: number): number [ES6]

Returns the logarithm of x to base 2. The inverse of 2 ** x.

> Math.log2(1)
0
> Math.log2(2)
1
> Math.log2(4)
2

View API entry online
Math.pow()

Math.pow(x: number, y: number): number [ES1]

Returns xy, x to the power of y. The same as x ** y.

> Math.pow(2, 3)
8
> Math.pow(25, 0.5)
5

View API entry online
Math.sqrt()

Math.sqrt(x: number): number [ES1]

Returns the square root of x. The inverse of x ** 2.

> Math.sqrt(9)
3

View API entry online
Math.ceil()

Math.ceil(x: number): number [ES1]

Returns the smallest (closest to −∞) integer i with xi.

> Math.ceil(2.1)
3
> Math.ceil(2.9)
3

View API entry online
Math.floor()

Math.floor(x: number): number [ES1]

Returns the largest (closest to +∞) integer i with ix.

> Math.floor(2.1)
2
> Math.floor(2.9)
2

View API entry online
Math.round()

Math.round(x: number): number [ES1]

Returns the integer that is closest to x. If the decimal fraction of x is .5 then .round() rounds up (to the integer closer to positive infinity):

> Math.round(2.4)
2
> Math.round(2.5)
3

View API entry online
Math.trunc()

Math.trunc(x: number): number [ES6]

Removes the decimal fraction of x and returns the resulting integer.

> Math.trunc(2.1)
2
> Math.trunc(2.9)
2

View API entry online
Math.fround()

Math.fround(x: number): number [ES6]

Rounds x to a 32-bit single float (within a 64-bit double float):

> Math.fround(2**128)
Infinity
> 2**128
3.402823669209385e+38

> Math.fround(2**-150)
0
> 2**-150
7.006492321624085e-46

View API entry online
Math.f16round()

Math.f16round(x: number): number [ES2025]

Rounds x to a 16-bit half-float (within a 64-bit double float):

> Math.f16round(2**16)
Infinity
> 2**16
65536

> Math.f16round(2**-25)
0
> 2**-25
2.9802322387695312e-8

View API entry online
Math.acos()

Math.acos(x: number): number [ES1]

Returns the arc cosine (inverse cosine) of x.

> Math.acos(0)
1.5707963267948966
> Math.acos(1)
0

View API entry online
Math.acosh()

Math.acosh(x: number): number [ES6]

Returns the inverse hyperbolic cosine of x.


View API entry online
Math.asin()

Math.asin(x: number): number [ES1]

Returns the arc sine (inverse sine) of x.

> Math.asin(0)
0
> Math.asin(1)
1.5707963267948966

View API entry online
Math.asinh()

Math.asinh(x: number): number [ES6]

Returns the inverse hyperbolic sine of x.


View API entry online
Math.atan()

Math.atan(x: number): number [ES1]

Returns the arc tangent (inverse tangent) of x.


View API entry online
Math.atanh()

Math.atanh(x: number): number [ES6]

Returns the inverse hyperbolic tangent of x.


View API entry online
Math.atan2()

Math.atan2(y: number, x: number): number [ES1]

Returns the arc tangent of the quotient y/x.


View API entry online
Math.cos()

Math.cos(x: number): number [ES1]

Returns the cosine of x.

> Math.cos(0)
1
> Math.cos(Math.PI)
-1

View API entry online
Math.cosh()

Math.cosh(x: number): number [ES6]

Returns the hyperbolic cosine of x.


View API entry online
Math.hypot()

Math.hypot(...values: Array<number>): number [ES6]

Returns the square root of the sum of the squares of values (Pythagoras’ theorem):

> Math.hypot(3, 4)
5

View API entry online
Math.sin()

Math.sin(x: number): number [ES1]

Returns the sine of x.

> Math.sin(0)
0
> Math.sin(Math.PI / 2)
1

View API entry online
Math.sinh()

Math.sinh(x: number): number [ES6]

Returns the hyperbolic sine of x.


View API entry online
Math.tan()

Math.tan(x: number): number [ES1]

Returns the tangent of x.

> Math.tan(0)
0
> Math.tan(1)
1.5574077246549023

View API entry online
Math.tanh()

Math.tanh(x: number): number; [ES6]

Returns the hyperbolic tangent of x.


View API entry online
Math.abs()

Math.abs(x: number): number [ES1]

Returns the absolute value of x.

> Math.abs(3)
3
> Math.abs(-3)
3
> Math.abs(0)
0

View API entry online
Math.clz32()

Math.clz32(x: number): number [ES6]

Counts the leading zero bits in the 32-bit integer x. Used in DSP algorithms.

> Math.clz32(0b01000000000000000000000000000000)
1
> Math.clz32(0b00100000000000000000000000000000)
2
> Math.clz32(2)
30
> Math.clz32(1)
31

View API entry online
Math.max()

Math.max(...values: Array<number>): number [ES1]

Converts values to numbers and returns the largest one.

> Math.max(3, -5, 24)
24

View API entry online
Math.min()

Math.min(...values: Array<number>): number [ES1]

Converts values to numbers and returns the smallest one.

> Math.min(3, -5, 24)
-5

View API entry online
Math.random()

Math.random(): number [ES1]

Returns a pseudo-random number n where 0 ≤ n < 1.

/** Returns a random integer i with 0 <= i < max */
function getRandomInteger(max) {
  return Math.floor(Math.random() * max);
}

View API entry online
Math.sign()

Math.sign(x: number): number [ES6]

Returns the sign of a number:

> Math.sign(-8)
-1
> Math.sign(0)
0
> Math.sign(3)
1

View API entry online
String.prototype.startsWith()

String.prototype.startsWith(searchString, startPos=0) [ES6]

Returns true if searchString occurs in the string at index startPos. Returns false otherwise.

> '.gitignore'.startsWith('.')
true
> 'abcde'.startsWith('bc', 1)
true

View API entry online
String.prototype.endsWith()

String.prototype.endsWith(searchString, endPos=this.length) [ES6]

Returns true if the string would end with searchString if its length were endPos. Returns false otherwise.

> 'poem.txt'.endsWith('.txt')
true
> 'abcde'.endsWith('cd', 4)
true

View API entry online
String.prototype.includes()

String.prototype.includes(searchString, startPos=0) [ES6]

Returns true if the string contains the searchString and false otherwise. The search starts at startPos.

> 'abc'.includes('b')
true
> 'abc'.includes('b', 2)
false

View API entry online
String.prototype.indexOf()

String.prototype.indexOf(searchString, minIndex=0) [ES1]

> 'aaax'.indexOf('aa', 0)
0
> 'aaax'.indexOf('aa', 1)
1
> 'aaax'.indexOf('aa', 2)
-1

View API entry online
String.prototype.lastIndexOf()

String.prototype.lastIndexOf(searchString, maxIndex?) [ES1]

> 'xaaa'.lastIndexOf('aa', 3)
2
> 'xaaa'.lastIndexOf('aa', 2)
2
> 'xaaa'.lastIndexOf('aa', 1)
1
> 'xaaa'.lastIndexOf('aa', 0)
-1

View API entry online
String.prototype.slice()

String.prototype.slice(start=0, end=this.length) [ES3]

Returns the substring of the string that starts at (including) index start and ends at (excluding) index end. If an index is negative, it is added to .length before it is used (-1 becomes this.length-1, etc.).

> 'abc'.slice(1, 3)
'bc'
> 'abc'.slice(1)
'bc'
> 'abc'.slice(-2)
'bc'

View API entry online
String.prototype.at()

String.prototype.at(index: number) [ES2022]

> 'abc'.at(0)
'a'
> 'abc'.at(-1)
'c'

View API entry online
String.prototype.substring()

String.prototype.substring(start, end=this.length) [ES1]

Use .slice() instead of this method. .substring() wasn’t implemented consistently in older engines and doesn’t support negative indices.


View API entry online
String.prototype.concat()

String.prototype.concat(...strings) [ES3]

Returns the concatenation of the string and strings. 'a'.concat('b') is equivalent to 'a'+'b'. The latter is much more popular.

> 'ab'.concat('cd', 'ef', 'gh')
'abcdefgh'

View API entry online
String.prototype.padEnd()

String.prototype.padEnd(len, fillString=' ') [ES2017]

Appends (fragments of) fillString to the string until it has the desired length len. If it already has or exceeds len, then it is returned without any changes.

> '#'.padEnd(2)
'# '
> 'abc'.padEnd(2)
'abc'
> '#'.padEnd(5, 'abc')
'#abca'

View API entry online
String.prototype.padStart()

String.prototype.padStart(len, fillString=' ') [ES2017]

Prepends (fragments of) fillString to the string until it has the desired length len. If it already has or exceeds len, then it is returned without any changes.

> '#'.padStart(2)
' #'
> 'abc'.padStart(2)
'abc'
> '#'.padStart(5, 'abc')
'abca#'

View API entry online
String.prototype.repeat()

String.prototype.repeat(count=0) [ES6]

Returns the string, concatenated count times.

> '*'.repeat()
''
> '*'.repeat(3)
'***'

View API entry online
String.prototype.toUpperCase()

String.prototype.toUpperCase() [ES1]

Returns a copy of the string in which all lowercase alphabetic characters are converted to uppercase. How well that works for various alphabets, depends on the JavaScript engine.

> '-a2b-'.toUpperCase()
'-A2B-'
> 'αβγ'.toUpperCase()
'ΑΒΓ'

View API entry online
String.prototype.toLowerCase()

String.prototype.toLowerCase() [ES1]

Returns a copy of the string in which all uppercase alphabetic characters are converted to lowercase. How well that works for various alphabets, depends on the JavaScript engine.

> '-A2B-'.toLowerCase()
'-a2b-'
> 'ΑΒΓ'.toLowerCase()
'αβγ'

View API entry online
String.prototype.trim()

String.prototype.trim() [ES5]

Returns a copy of the string in which all leading and trailing whitespace (spaces, tabs, line terminators, etc.) is gone.

> '\r\n#\t  '.trim()
'#'
> '  abc  '.trim()
'abc'

View API entry online
String.prototype.trimStart()

String.prototype.trimStart() [ES2019]

Similar to .trim() but only the beginning of the string is trimmed:

> '  abc  '.trimStart()
'abc  '

View API entry online
String.prototype.trimEnd()

String.prototype.trimEnd() [ES2019]

Similar to .trim() but only the end of the string is trimmed:

> '  abc  '.trimEnd()
'  abc'

View API entry online
String.prototype.normalize()

String.prototype.normalize(form = 'NFC') [ES6]


View API entry online
String.prototype.isWellFormed()

String.prototype.isWellFormed() [ES2024]

Returns true if a string is ill-formed and contains lone surrogates (see .toWellFormed() for more information). Otherwise, it returns false.

> '🙂'.split('') // split into code units
[ '\uD83D', '\uDE42' ]
> '\uD83D\uDE42'.isWellFormed()
true
> '\uD83D\uDE42\uD83D'.isWellFormed() // lone surrogate 0xD83D
false

View API entry online
String.prototype.toWellFormed()

String.prototype.toWellFormed() [ES2024]

Each JavaScript string character is a UTF-16 code unit. One code point is encoded as either one UTF-16 code unit or two UTF-16 code unit. In the latter case, the two code units are called leading surrogate and trailing surrogate. A surrogate without its partner is called a lone surrogate. A string with one or more lone surrogates is ill-formed.

.toWellFormed() converts an ill-formed string to a well-formed one by replacing each lone surrogate with code point 0xFFFD (“replacement character”). That character is often displayed as a � (a black rhombus with a white question mark). It is located in the Specials Unicode block of characters, at the very end of the Basic Multilingual Plane. This is what Wikipedia says about the replacement character: “It is used to indicate problems when a system is unable to render a stream of data to correct symbols.”

assert.deepEqual(
  '🙂'.split(''), // split into code units
  ['\uD83D', '\uDE42']
);
assert.deepEqual(
   // 0xD83D is a lone surrogate
  '\uD83D\uDE42\uD83D'.toWellFormed().split(''),
  ['\uD83D', '\uDE42', '\uFFFD']
);

View API entry online
Object.create()

Object.create(proto, propDescObj?) [ES5]

> const obj = Object.create(null);
> Object.getPrototypeOf(obj)
null

In the following example, we define own properties via the second parameter:

const obj = Object.create(
  null,
  {
    color: {
      value: 'green',
      writable: true,
      enumerable: true,
      configurable: true,
    },
  }
);
assert.deepEqual(
  obj,
  {
    __proto__: null,
    color: 'green',
  }
);

View API entry online
Object.getPrototypeOf()

Object.getPrototypeOf(obj) [ES5]

Return the prototype of obj – which is either an object or null.

assert.equal(
  Object.getPrototypeOf({__proto__: null}), null
);
assert.equal(
  Object.getPrototypeOf({}), Object.prototype
);
assert.equal(
  Object.getPrototypeOf(Object.prototype), null
);

View API entry online
Object.setPrototypeOf()

Object.setPrototypeOf(obj, proto) [ES6]

Sets the prototype of obj to proto (which must be null or an object) and returns the former.

const obj = {};
assert.equal(
  Object.getPrototypeOf(obj), Object.prototype
);
Object.setPrototypeOf(obj, null);
assert.equal(
  Object.getPrototypeOf(obj), null
);

View API entry online
Object.defineProperty()

Object.defineProperty(obj, propKey, propDesc) [ES5]

const obj = {};
Object.defineProperty(
  obj, 'color',
  {
    value: 'green',
    writable: true,
    enumerable: true,
    configurable: true,
  }
);
assert.deepEqual(
  obj,
  {
    color: 'green',
  }
);

View API entry online
Object.defineProperties()

Object.defineProperties(obj, propDescObj) [ES5]

const obj = {};
Object.defineProperties(
  obj,
  {
    color: {
      value: 'green',
      writable: true,
      enumerable: true,
      configurable: true,
    },
  }
);
assert.deepEqual(
  obj,
  {
    color: 'green',
  }
);

View API entry online
Object.getOwnPropertyDescriptor()

Object.getOwnPropertyDescriptor(obj, propKey) [ES5]

> Object.getOwnPropertyDescriptor({a: 1, b: 2}, 'a')
{ value: 1, writable: true, enumerable: true, configurable: true }
> Object.getOwnPropertyDescriptor({a: 1, b: 2}, 'x')
undefined

View API entry online
Object.getOwnPropertyDescriptors()

Object.getOwnPropertyDescriptors(obj) [ES2017]

> Object.getOwnPropertyDescriptors({a: 1, b: 2})
{
  a: { value: 1, writable: true, enumerable: true, configurable: true },
  b: { value: 2, writable: true, enumerable: true, configurable: true },
}

View API entry online
Object.keys()

Object.keys(obj) [ES5]

Returns an Array with all own enumerable property keys that are strings.

const enumSymbolKey = Symbol('enumSymbolKey');
const nonEnumSymbolKey = Symbol('nonEnumSymbolKey');

const obj = Object.defineProperties(
  {},
  {
    enumStringKey: {
      value: 1, enumerable: true,
    },
    [enumSymbolKey]: {
      value: 2, enumerable: true,
    },
    nonEnumStringKey: {
      value: 3, enumerable: false,
    },
    [nonEnumSymbolKey]: {
      value: 4, enumerable: false,
    },
  }
);
assert.deepEqual(
  Object.keys(obj),
  ['enumStringKey']
);

View API entry online
Object.getOwnPropertyNames()

Object.getOwnPropertyNames(obj) [ES5]

Returns an Array with all own property keys that are strings (enumerable and non-enumerable ones).

const enumSymbolKey = Symbol('enumSymbolKey');
const nonEnumSymbolKey = Symbol('nonEnumSymbolKey');

const obj = Object.defineProperties(
  {},
  {
    enumStringKey: {
      value: 1, enumerable: true,
    },
    [enumSymbolKey]: {
      value: 2, enumerable: true,
    },
    nonEnumStringKey: {
      value: 3, enumerable: false,
    },
    [nonEnumSymbolKey]: {
      value: 4, enumerable: false,
    },
  }
);
assert.deepEqual(
  Object.getOwnPropertyNames(obj),
  ['enumStringKey', 'nonEnumStringKey']
);

View API entry online
Object.getOwnPropertySymbols()

Object.getOwnPropertySymbols(obj) [ES6]

Returns an Array with all own property keys that are symbols (enumerable and non-enumerable ones).

const enumSymbolKey = Symbol('enumSymbolKey');
const nonEnumSymbolKey = Symbol('nonEnumSymbolKey');

const obj = Object.defineProperties(
  {},
  {
    enumStringKey: {
      value: 1, enumerable: true,
    },
    [enumSymbolKey]: {
      value: 2, enumerable: true,
    },
    nonEnumStringKey: {
      value: 3, enumerable: false,
    },
    [nonEnumSymbolKey]: {
      value: 4, enumerable: false,
    },
  }
);
assert.deepEqual(
  Object.getOwnPropertySymbols(obj),
  [enumSymbolKey, nonEnumSymbolKey]
);

View API entry online
Object.values()

Object.values(obj) [ES2017]

Returns an Array with the values of all enumerable own string-keyed properties.

> Object.values({a: 1, b: 2})
[ 1, 2 ]

View API entry online
Object.entries()

Object.entries(obj) [ES2017]

const obj = {
  a: 1,
  b: 2,
  [Symbol('myKey')]: 3,
};
assert.deepEqual(
  Object.entries(obj),
  [
    ['a', 1],
    ['b', 2],
    // Property with symbol key is ignored
  ]
);

View API entry online
Object.fromEntries()

Object.fromEntries(keyValueIterable) [ES2019]

> Object.fromEntries([['a', 1], ['b', 2]])
{ a: 1, b: 2 }

View API entry online
Object.hasOwn()

Object.hasOwn(obj, key) [ES2022]

> Object.hasOwn({a: 1, b: 2}, 'a')
true
> Object.hasOwn({a: 1, b: 2}, 'x')
false

View API entry online
Object.preventExtensions()

Object.preventExtensions(obj) [ES5]


View API entry online
Object.isExtensible()

Object.isExtensible(obj) [ES5]


View API entry online
Object.seal()

Object.seal(obj) [ES5]


View API entry online
Object.isSealed()

Object.isSealed(obj) [ES5]


View API entry online
Object.freeze()

Object.freeze(obj) [ES5]

const frozen = Object.freeze({ x: 2, y: 5 });
assert.equal(
  Object.isFrozen(frozen), true
);
assert.throws(
  () => frozen.x = 7,
  {
    name: 'TypeError',
    message: /^Cannot assign to read only property 'x'/,
  }
);

View API entry online
Object.isFrozen()

Object.isFrozen(obj) [ES5]


View API entry online
Object.assign()

Object.assign(target, ...sources) [ES6]

Assigns all enumerable own string-keyed properties of each of the sources to target and returns target.

> const obj = {a: 1, b: 1};
> Object.assign(obj, {b: 2, c: 2}, {d: 3})
{ a: 1, b: 2, c: 2, d: 3 }
> obj
{ a: 1, b: 2, c: 2, d: 3 }

View API entry online
Object.groupBy()

Object.groupBy(items, computeGroupKey) [ES2024]

Object.groupBy<K extends PropertyKey, T>(
  items: Iterable<T>,
  computeGroupKey: (item: T, index: number) => K,
): {[key: K]: Array<T>}
assert.deepEqual(
  Object.groupBy(
    ['orange', 'apricot', 'banana', 'apple', 'blueberry'],
    (str) => str[0] // compute group key
  ),
  {
    __proto__: null,
    'o': ['orange'],
    'a': ['apricot', 'apple'],
    'b': ['banana', 'blueberry'],
  }
);

View API entry online
Object.is()

Object.is(value1, value2) [ES6]

Is mostly equivalent to value1 === value2 – with two exceptions:

> NaN === NaN
false
> Object.is(NaN, NaN)
true

> -0 === 0
true
> Object.is(-0, 0)
false

View API entry online
Reflect.apply()

Reflect.apply(target, thisArgument, argumentsList) [ES6]


View API entry online
Reflect.construct()

Reflect.construct(target, argumentsList, newTarget=target) [ES6]


View API entry online
Reflect.defineProperty()

Reflect.defineProperty(target, propertyKey, propDesc) [ES6]


View API entry online
Reflect.deleteProperty()

Reflect.deleteProperty(target, propertyKey) [ES6]

The delete operator as a function. It works slightly differently, though:

In sloppy mode, the delete operator returns the same results as this method. But in strict mode, it throws a TypeError instead of returning false.

The only way to protect properties from deletion is by making them non-configurable.


View API entry online
Reflect.get()

Reflect.get(target, propertyKey, receiver=target) [ES6]

A function that gets properties. The optional parameter receiver is needed if get reaches a getter (somewhere in the prototype chain). Then it provides the value for this.


View API entry online
Reflect.getOwnPropertyDescriptor()

Reflect.getOwnPropertyDescriptor(target, propertyKey) [ES6]

Same as Object.getOwnPropertyDescriptor().


View API entry online
Reflect.getPrototypeOf()

Reflect.getPrototypeOf(target) [ES6]

Same as Object.getPrototypeOf().


View API entry online
Reflect.has()

Reflect.has(target, propertyKey) [ES6]

The in operator as a function.


View API entry online
Reflect.isExtensible()

Reflect.isExtensible(target) [ES6]

Same as Object.isExtensible().


View API entry online
Reflect.ownKeys()

Reflect.ownKeys(target) [ES6]

Returns all own property keys (strings and symbols) in an Array.


View API entry online
Reflect.preventExtensions()

Reflect.preventExtensions(target) [ES6]


View API entry online
Reflect.set()

Reflect.set(target, propertyKey, value, receiver=target) [ES6]


View API entry online
Reflect.setPrototypeOf()

Reflect.setPrototypeOf(target, proto) [ES6]


View API entry online
Object.prototype.toString()

Object.prototype.toString() [ES1]

Configures how an object is converted to a string.

> 'Object: ' + {toString() {return 'Hello!'}}
'Object: Hello!'

More information.


View API entry online
Object.prototype.toLocaleString()

Object.prototype.toLocaleString() [ES3]

A version of .toString() that can be configured in various ways via arguments (language, region, etc.). More information.


View API entry online
Object.prototype.valueOf()

Object.prototype.valueOf() [ES1]

Configures how an object is converted to a non-string primitive value (often a number).

> 1 + {valueOf() {return 123}}
124

More information.


View API entry online
Object.prototype.isPrototypeOf()

Object.prototype.isPrototypeOf() [ES3]

Is the receiver in the prototype chain of a given object?

You’ll usually be fine if you invoke this method on an object. If you want to be safe, you can use the following pattern (line A):

function isInstanceOf(obj, aClass) {
  return {}.isPrototypeOf.call(aClass.prototype, obj); // (A)
}
assert.equal(
  isInstanceOf([], Object), true
);
assert.equal(
  isInstanceOf([], Array), true
);
assert.equal(
  isInstanceOf(/x/, Array), false
);

More information.


View API entry online
Object.prototype.propertyIsEnumerable()

Object.prototype.propertyIsEnumerable() [ES3]

Does the receiver have an enumerable own property with the given key?

You’ll usually be fine if you invoke this method on an object. If you want to be safe, you can use the following pattern:

> {}.propertyIsEnumerable.call(['a'], 'length')
false
> {}.propertyIsEnumerable.call(['a'], '0')
true

More information.


View API entry online
get Object.prototype.__proto__

get Object.prototype.__proto__ [ES6]

Avoid:


View API entry online
set Object.prototype.__proto__

set Object.prototype.__proto__ [ES6]

Avoid:


View API entry online
Object.prototype.hasOwnProperty()

Object.prototype.hasOwnProperty [ES3]

Avoid:


View API entry online
Iterator.prototype.drop()

Iterator.prototype.drop(limit) [ES2025]

Iterator<T>.prototype.drop(limit: number): Iterator<T>

This method returns an iterator that with all values of iterator, except for the first limit ones. That is, iteration starts when the iteration counter is limit.

assert.deepEqual(
  Iterator.from(['a', 'b', 'c', 'd']).drop(1).toArray(),
  ['b', 'c', 'd']
);

View API entry online
Iterator.prototype.filter()

Iterator.prototype.filter(filterFn) [ES2025 | Callback gets counter]

Iterator<T>.prototype.filter(
  filterFn: (value: T, counter: number) => boolean
): Iterator<T>

This method returns an iterator whose values are the values of iterator for which filterFn returns true.

assert.deepEqual(
  Iterator.from(['a', 'b', 'c', 'd']).filter(x => x <= 'b').toArray(),
  ['a', 'b']
);

View API entry online
Iterator.prototype.flatMap()

Iterator.prototype.flatMap(mapFn) [ES2025 | Callback gets counter]

Iterator<T>.prototype.flatMap<U>(
  mapFn: (value: T, counter: number) => Iterable<U> | Iterator<U>
): Iterator<U>

This method returns an iterator whose values are the values of the iterables or iterators that are the results of applying mapFn to the values of iterator.

assert.deepEqual(
  Iterator.from(['a', 'b', 'c', 'd'])
  .flatMap((value, counter) => new Array(counter).fill(value))
  .toArray(),
  ['b', 'c', 'c', 'd', 'd', 'd']
);

For more information see the section on the Array method with the same name: .flatMap(): Each input element produces zero or more output elements 2019.


View API entry online
Iterator.prototype.map()

Iterator.prototype.map(mapFn) [ES2025 | Callback gets counter]

Iterator<T>.prototype.map<U>(
  mapFn: (value: T, counter: number) => U
): Iterator<U>

This method returns an iterator whose values are the result of applying mapFn to the values of iterator.

assert.deepEqual(
  Iterator.from(['a', 'b', 'c', 'd']).map(x => x + x).toArray(),
  ['aa', 'bb', 'cc', 'dd']
);

View API entry online
Iterator.prototype.take()

Iterator.prototype.take(limit) [ES2025]

Iterator<T>.prototype.take(limit: number): Iterator<T>

This method returns an iterator with the first limit values of iterator.

assert.deepEqual(
  Iterator.from(['a', 'b', 'c', 'd']).take(1).toArray(),
  ['a']
);

View API entry online
Iterator.prototype.every()

Iterator.prototype.every(fn) [ES2025 | Callback gets counter]

Iterator<T>.prototype.every(
  fn: (value: T, counter: number) => boolean
): boolean

This method returns true if fn returns true for every value of iterator. Otherwise, it returns false.

assert.equal(
  Iterator.from(['a', 'b', 'c', 'd']).every(x => x === 'c'),
  false
);

View API entry online
Iterator.prototype.some()

Iterator.prototype.some(fn) [ES2025 | Callback gets counter]

Iterator<T>.prototype.some(
  fn: (value: T, counter: number) => boolean
): boolean

This method returns true if fn returns true for at least one value of iterator. Otherwise, it returns false.

assert.equal(
  Iterator.from(['a', 'b', 'c', 'd']).some(x => x === 'c'),
  true
);

View API entry online
Iterator.prototype.find()

Iterator.prototype.find(fn) [ES2025 | Callback gets counter]

Iterator<T>.prototype.find(
  fn: (value: T, counter: number) => boolean
): T

This method returns the first value of iterator for which fn returns true. If there is no such value, it returns undefined.

assert.equal(
  Iterator.from(['a', 'b', 'c', 'd']).find((_, counter) => counter === 1),
  'b'
);

View API entry online
Iterator.prototype.reduce()

Iterator.prototype.reduce(reducer, initialValue?) [ES2025 | Callback gets counter]

Iterator<T>.prototype.reduce<U>(
  reducer: (accumulator: U, value: T, counter: number) => U,
  initialValue?: U
): U

This method uses the function reducer to combine the values of iterator into a single value.

Example – concatenating the strings of an iterator:

assert.deepEqual(
  Iterator.from(['a', 'b', 'c', 'd']).reduce((acc, v) => acc + v),
  'abcd'
);

Example – computing the minimum of a Set of numbers:

const set = new Set([3, -2, -5, 4]);
assert.equal(
  set.values().reduce((min, cur) => cur < min ? cur : min, Infinity),
  -5
);

For more information see the section on the Array method with the same name: .reduce(): computing a summary for an Array”.


View API entry online
Iterator.prototype.toArray()

Iterator.prototype.toArray() [ES2025]

Iterator<T>.prototype.toArray(): Array<T>

This method returns the values of iterator in an Array.

assert.deepEqual(
  Iterator.from(['a', 'b', 'c', 'd']).toArray(),
  ['a', 'b', 'c', 'd']
);

View API entry online
Iterator.prototype.forEach()

Iterator.prototype.forEach(fn) [ES2025 | Callback gets counter]

Iterator<T>.prototype.forEach(
  fn: (value: T, counter: number) => void
): void

This method applies fn to each value in iterator.

const result = [];
Iterator.from(['a', 'b', 'c', 'd']).forEach(x => result.unshift(x))
assert.deepEqual(
  result,
  ['d', 'c', 'b', 'a']
);

View API entry online
new Array()

new Array(len = 0) [ES1]

Creates an Array of length len that only contains holes:

// Trailing commas are always ignored.
// Therefore: number of commas = number of holes
assert.deepEqual(new Array(3), [,,,]);

View API entry online
Array.from()

Array.from(iterableOrArrayLike, mapFunc?) [ES6]

Array.from<T>(
  iterableOrArrayLike: Iterable<T> | ArrayLike<T>
): Array<T>
Array.from<T, U>(
  iterableOrArrayLike: Iterable<T> | ArrayLike<T>,
  mapFunc: (v: T, k: number) => U, thisArg?: any
): Array<U>

Examples:

> Array.from(new Set(['a', 'b'])) // iterable
[ 'a', 'b' ]
> Array.from({length: 2, 0:'a', 1:'b'}) // Array-like object
[ 'a', 'b' ]

View API entry online
Array.of()

Array.of(...items) [ES6]

Array.of<T>(
  ...items: Array<T>
): Array<T>

This static method is mainly useful for subclasses of Array, where it serves as a custom Array literal:

class MyArray extends Array {}

assert.equal(
  MyArray.of('a', 'b') instanceof MyArray, true
);

View API entry online
Array.prototype.at()

Array.prototype.at(index) [ES2022 | Non-mutating]

This method is mostly equivalent to getting elements via square brackets:

arr[index] === arr.at(index)

One reason for using .at() is that it supports negative indices:

> ['a', 'b', 'c'].at(0)
'a'
> ['a', 'b', 'c'].at(-1)
'c'

View API entry online
Array.prototype.with()

Array.prototype.with(index, value) [ES2023 | Non-mutating]

This method is the non-destructive version of setting elements via square brackets. It supports negative indices:

> ['a', 'b', 'c'].with(2, 'x')
[ 'a', 'b', 'x' ]
> ['a', 'b', 'c'].with(-1, 'x')
[ 'a', 'b', 'x' ]

View API entry online
Array.prototype.forEach()

Array.prototype.forEach(callback) [ES5 | Non-mutating]

Array<T>.prototype.forEach(
  callback: (value: T, index: number, array: Array<T>) => void,
  thisArg?: any
): void

Calls callback for each element.

['a', 'b'].forEach(
  (elem) => console.log(elem)
);
['a', 'b'].forEach(
  (elem, index) => console.log(elem, index)
);

Output:

a
b
a 0
b 1

A for-of loop is usually a better choice: it’s faster, supports break and can iterate over arbitrary iterables.


View API entry online
Array.prototype.keys()

Array.prototype.keys() [ES6 | Non-mutating]

Returns an iterable over the keys of the receiver.

> Array.from(['a', 'b'].keys())
[ 0, 1 ]

View API entry online
Array.prototype.values()

Array.prototype.values() [ES6 | Non-mutating]

Returns an iterable over the values of the receiver.

> Array.from(['a', 'b'].values())
[ 'a', 'b' ]

View API entry online
Array.prototype.entries()

Array.prototype.entries() [ES6 | Non-mutating]

Returns an iterable over [index, element] pairs.

> Array.from(['a', 'b'].entries())
[ [ 0, 'a' ], [ 1, 'b' ] ]

View API entry online
Array.prototype.pop()

Array.prototype.pop() [ES3 | Mutating]

Removes and returns the last element of the receiver. That is, it treats the end of the receiver as a stack. The opposite of .push().

> const arr = ['a', 'b', 'c'];
> arr.pop()
'c'
> arr
[ 'a', 'b' ]

View API entry online
Array.prototype.push()

Array.prototype.push(...items) [ES3 | Mutating]

Adds zero or more items to the end of the receiver. That is, it treats the end of the receiver as a stack. The return value is the length of the receiver after the change. The opposite of .pop().

> const arr = ['a', 'b'];
> arr.push('c', 'd')
4
> arr
[ 'a', 'b', 'c', 'd' ]

We can push an Array by spreading (...) it into arguments:

> const arr = ['x'];
> arr.push(...['y', 'z'])
3
> arr
[ 'x', 'y', 'z' ]  

View API entry online
Array.prototype.shift()

Array.prototype.shift() [ES3 | Mutating]

Removes and returns the first element of the receiver. The inverse of .unshift().

> const arr = ['a', 'b', 'c'];
> arr.shift()
'a'
> arr
[ 'b', 'c' ]

View API entry online
Array.prototype.unshift()

Array.prototype.unshift(...items) [ES3 | Mutating]

Inserts the items at the beginning of the receiver and returns its length after this modification.

> const arr = ['c', 'd'];
> arr.unshift('e', 'f')
4
> arr
[ 'e', 'f', 'c', 'd' ]

We can push an Array by spreading (...) it into arguments:

> const arr = ['c'];
> arr.unshift(...['a', 'b'])
3
> arr
[ 'a', 'b', 'c' ]

View API entry online
Array.prototype.concat()

Array.prototype.concat(...items) [ES3 | Non-mutating]

Returns a new Array that is the concatenation of the receiver and all items. Non-Array parameters (such as 'b' in the following example) are treated as if they were Arrays with single elements.

> ['a'].concat('b', ['c', 'd'])
[ 'a', 'b', 'c', 'd' ]

View API entry online
Array.prototype.slice()

Array.prototype.slice(start?, end?) [ES3 | Non-mutating]

Returns a new Array containing the elements of the receiver whose indices are between (including) start and (excluding) end.

> ['a', 'b', 'c', 'd'].slice(1, 3)
[ 'b', 'c' ]
> ['a', 'b'].slice() // shallow copy
[ 'a', 'b' ]

.slice() supports negative indices:

> ['a', 'b', 'c'].slice(-2)
[ 'b', 'c' ]

It can be used to (shallowly) copy Arrays:

const copy = original.slice();

View API entry online
Array.prototype.splice()

Array.prototype.splice(start?, deleteCount?, ...items) [ES3 | Mutating]

> const arr = ['a', 'b', 'c', 'd'];
> arr.splice(1, 2, 'x', 'y')
[ 'b', 'c' ]
> arr
[ 'a', 'x', 'y', 'd' ]

If deleteCount is missing, .splice() deletes until the end of the Array:

> const arr = ['a', 'b', 'c', 'd'];
> arr.splice(2)
[ 'c', 'd' ]
> arr
[ 'a', 'b' ]

start can be negative:

> ['a', 'b', 'c'].splice(-2)
[ 'b', 'c' ]

View API entry online
Array.prototype.toSpliced()

Array.prototype.toSpliced(start?, deleteCount?, ...items) [ES2023 | Non-mutating]

> const arr = ['a', 'b', 'c', 'd'];
> arr.toSpliced(1, 2, 'x', 'y')
[ 'a', 'x', 'y', 'd' ]

start can be negative:

> ['a', 'b', 'c'].toSpliced(-2)
[ 'a' ]

View API entry online
Array.prototype.fill()

Array.prototype.fill(start=0, end=this.length) [ES6 | Mutating]

> [0, 1, 2].fill('a')
[ 'a', 'a', 'a' ]

Caveat: Don’t use this method to fill an Array with an object obj; then each element will refer to the same value (sharing it). In this case, it’s better to use Array.from().


View API entry online
Array.prototype.copyWithin()

Array.prototype.copyWithin(target, start, end=this.length) [ES6 | Mutating]

Copies the elements whose indices range from (including) start to (excluding) end to indices starting with target. Overlapping is handled correctly.

> ['a', 'b', 'c', 'd'].copyWithin(0, 2, 4)
[ 'c', 'd', 'c', 'd' ]

start or end can be negative.


View API entry online
Array.prototype.includes()

Array.prototype.includes(searchElement, fromIndex) [ES2016 | Non-mutating]

Returns true if the receiver has an element whose value is searchElement and false, otherwise. Searching starts at index fromIndex.

> [0, 1, 2].includes(1)
true
> [0, 1, 2].includes(5)
false

View API entry online
Array.prototype.indexOf()

Array.prototype.indexOf(searchElement, fromIndex) [ES5 | Non-mutating]

Returns the index of the first element that is strictly equal to searchElement. Returns -1 if there is no such element. Starts searching at index fromIndex, visiting higher indices next.

> ['a', 'b', 'a'].indexOf('a')
0
> ['a', 'b', 'a'].indexOf('a', 1)
2
> ['a', 'b', 'a'].indexOf('c')
-1

View API entry online
Array.prototype.lastIndexOf()

Array.prototype.lastIndexOf(searchElement, fromIndex) [ES5 | Non-mutating]

Returns the index of the last element that is strictly equal to searchElement. Returns -1 if there is no such element. Starts searching at index fromIndex, visiting lower indices next.

> ['a', 'b', 'a'].lastIndexOf('a')
2
> ['a', 'b', 'a'].lastIndexOf('a', 1)
0
> ['a', 'b', 'a'].lastIndexOf('c')
-1

View API entry online
Array.prototype.find()

Array.prototype.find(predicate, thisArg?) [ES6 | Non-mutating]

Array<T>.prototype.find(
  predicate: (value: T, index: number, obj: Array<T>) => boolean,
  thisArg?: any
): T | undefined
> [-1, 2, -3].find(x => x < 0)
-1
> [1, 2, 3].find(x => x < 0)
undefined

View API entry online
Array.prototype.findLast()

Array.prototype.findLast(predicate, thisArg?) [ES2023 | Non-mutating]

Array<T>.prototype.findLast(
  predicate: (value: T, index: number, obj: Array<T>) => boolean,
  thisArg?: any
): T | undefined
> [-1, 2, -3].findLast(x => x < 0)
-3
> [1, 2, 3].findLast(x => x < 0)
undefined

View API entry online
Array.prototype.findIndex()

Array.prototype.findIndex(predicate, thisArg?) [ES6 | Non-mutating]

Array<T>.prototype.findIndex(
  predicate: (value: T, index: number, obj: Array<T>) => boolean,
  thisArg?: any
): number
> [-1, 2, -3].findIndex(x => x < 0)
0
> [1, 2, 3].findIndex(x => x < 0)
-1

View API entry online
Array.prototype.findLastIndex()

Array.prototype.findLastIndex(predicate, thisArg?) [ES2023 | Non-mutating]

Array<T>.prototype.findLastIndex(
  predicate: (value: T, index: number, obj: Array<T>) => boolean,
  thisArg?: any
): number
> [-1, 2, -3].findLastIndex(x => x < 0)
2
> [1, 2, 3].findLastIndex(x => x < 0)
-1

View API entry online
Array.prototype.filter()

Array.prototype.filter(predicate, thisArg?) [ES5 | Non-mutating]

Array<T>.prototype.filter(
  predicate: (value: T, index: number, array: Array<T>) => boolean,
  thisArg?: any
): Array<T>

Returns an Array with only those elements for which predicate returns a truthy value.

> [1, -2, 3].filter(x => x > 0)
[ 1, 3 ]

View API entry online
Array.prototype.map()

Array.prototype.map(callback, thisArg?) [ES5 | Non-mutating]

Array<T>.prototype.map<U>(
  mapFunc: (value: T, index: number, array: Array<T>) => U,
  thisArg?: any
): Array<U>

Returns a new Array, in which every element is the result of mapFunc being applied to the corresponding element of the receiver.

> [1, 2, 3].map(x => x * 2)
[ 2, 4, 6 ]
> ['a', 'b', 'c'].map((x, i) => i)
[ 0, 1, 2 ]

View API entry online
Array.prototype.flatMap()

Array.prototype.flatMap(callback, thisArg?) [ES2019 | Non-mutating]

Array<T>.prototype.flatMap<U>(
  callback: (value: T, index: number, array: Array<T>) => U|Array<U>,
  thisValue?: any
): Array<U>

The result is produced by invoking callback() for each element of the original Array and concatenating the Arrays it returns.

> ['a', 'b', 'c'].flatMap(x => [x,x])
[ 'a', 'a', 'b', 'b', 'c', 'c' ]
> ['a', 'b', 'c'].flatMap(x => [x])
[ 'a', 'b', 'c' ]
> ['a', 'b', 'c'].flatMap(x => [])
[]

View API entry online
Array.prototype.flat()

Array.prototype.flat(depth = 1) [ES2019 | Non-mutating]

“Flattens” an Array: It descends into the Arrays that are nested inside the input Array and creates a copy where all values it finds at level depth or lower are moved to the top level.

> [ 1,2, [3,4], [[5,6]] ].flat(0) // no change
[ 1, 2, [3,4], [[5,6]] ]

> [ 1,2, [3,4], [[5,6]] ].flat(1)
[1, 2, 3, 4, [5,6]]

> [ 1,2, [3,4], [[5,6]] ].flat(2)
[1, 2, 3, 4, 5, 6]

View API entry online
Array.prototype.every()

Array.prototype.every(predicate, thisArg?) [ES5 | Non-mutating]

Array<T>.prototype.every(
  predicate: (value: T, index: number, array: Array<T>) => boolean,
  thisArg?: any
): boolean

Returns true if predicate returns a truthy value for every element. Otherwise, it returns false:

> [1, 2, 3].every(x => x > 0)
true
> [1, -2, 3].every(x => x > 0)
false

View API entry online
Array.prototype.some()

Array.prototype.some(predicate, thisArg?) [ES5 | Non-mutating]

Array<T>.prototype.some(
  predicate: (value: T, index: number, array: Array<T>) => boolean,
  thisArg?: any
): boolean

Returns true if predicate returns a truthy value for at least one element. Otherwise, it returns false.

> [1, 2, 3].some(x => x < 0)
false
> [1, -2, 3].some(x => x < 0)
true

View API entry online
Array.prototype.reduce()

Array.prototype.reduce(callback, initialValue?) [ES5 | Non-mutating]

Array<T>.prototype.reduce<U>(
  callback: (accumulator: U, elem: T, idx: number, arr: Array<T>) => U,
  initialValue?: U
): U

This method produces a summary of the receiver: it feeds all Array elements to callback, which combines a current summary (in parameter accumulator) with the current Array element and returns the next accumulator:

const accumulator_0 = callback(initialValue, arr[0]);
const accumulator_1 = callback(accumulator_0, arr[1]);
const accumulator_2 = callback(accumulator_1, arr[2]);
// Etc.

The result of .reduce() is the last result of callback after it has visited all Array elements.

> [1, 2, 3].reduce((accu, x) => accu + x, 0)
6
> [1, 2, 3].reduce((accu, x) => accu + String(x), '')
'123'

If no initialValue is provided, the Array element at index 0 is used and the element at index 1 is visited first. Therefore, the Array must have at least length 1.


View API entry online
Array.prototype.reduceRight()

Array.prototype.reduceRight(callback, initialValue?) [ES5 | Non-mutating]

Array<T>.prototype.reduceRight<U>(
  callback: (accumulator: U, elem: T, idx: number, arr: Array<T>) => U,
  initialValue?: U
): U

Works like .reduce(), but visits the Array elements backward, starting with the last element.

> [1, 2, 3].reduceRight((accu, x) => accu + String(x), '')
'321'

View API entry online
Array.prototype.join()

Array.prototype.join(separator = ',') [ES1 | Non-mutating]

Creates a string by concatenating string representations of all elements, separating them with separator.

> ['a', 'b', 'c'].join('##')
'a##b##c'
> ['a', 'b', 'c'].join()
'a,b,c'

View API entry online
Array.prototype.toString()

Array.prototype.toString() [ES1 | Non-mutating]

Converts all elements to strings via String(), concatenates them while separating them with commas, and returns the result.

> [1, 2, 3].toString()
'1,2,3'
> ['1', '2', '3'].toString()
'1,2,3'
> [].toString()
''

View API entry online
Array.prototype.toLocaleString()

Array.prototype.toLocaleString() [ES3 | Non-mutating]

Works like .toString() but converts its elements to strings via .toLocaleString() (not via .toString()) before separating them via commas and concatenating them to a single string – that it returns.


View API entry online
Array.prototype.sort()

Array.prototype.sort(compareFunc?) [ES1 | Mutating]

Array<T>.prototype.sort(
  compareFunc?: (a: T, b: T) => number
): this

Sorting numbers:

// Default: lexicographical sorting
assert.deepEqual(
  [200, 3, 10].sort(),
  [10, 200, 3]
);

// Ascending numerical sorting (“from a to z”)
assert.deepEqual(
  [200, 3, 10].sort((a, z) => a - z),
  [3, 10, 200]
);

Sorting strings: By default, strings are sorted by code unit values (char codes), where, e.g., all unaccented uppercase letters come before all unaccented lowercase letters:

> ['pie', 'cookie', 'éclair', 'Pie', 'Cookie', 'Éclair'].sort()
[ 'Cookie', 'Pie', 'cookie', 'pie', 'Éclair', 'éclair' ]

For human languages, we can use Intl.Collator:

const arr = ['pie', 'cookie', 'éclair', 'Pie', 'Cookie', 'Éclair'];
assert.deepEqual(
  arr.sort(new Intl.Collator('en').compare),
  ['cookie', 'Cookie', 'éclair', 'Éclair', 'pie', 'Pie']
);

View API entry online
Array.prototype.toSorted()

Array.prototype.toSorted(compareFunc?) [ES2023 | Non-mutating]

Array<T>.prototype.toSorted.toSorted(
  compareFunc?: (a: T, b: T) => number
): Array<T>
const original = ['y', 'z', 'x'];
const sorted = original.toSorted();
assert.deepEqual(
  // The original is unchanged
  original, ['y', 'z', 'x']
);
assert.deepEqual(
  // The copy is sorted
  sorted, ['x', 'y', 'z']
);

See the description of .sort() for more information on how to use this method.


View API entry online
Array.prototype.reverse()

Array.prototype.reverse() [ES1 | Mutating]

Rearranges the elements of the receiver so that they are in reverse order and then returns the receiver.

> const arr = ['a', 'b', 'c'];
> arr.reverse()
[ 'c', 'b', 'a' ]
> arr
[ 'c', 'b', 'a' ]

The non-destructive version of this method is .toReversed().


View API entry online
Array.prototype.toReversed()

Array.prototype.toReversed() [ES2023 | Non-mutating]

const original = ['x', 'y', 'z'];
const reversed = original.toReversed();
assert.deepEqual(
  // The original is unchanged
  original, ['x', 'y', 'z']
);
assert.deepEqual(
  // The copy is reversed
  reversed, ['z', 'y', 'x']
);

View API entry online
new ArrayBuffer()

new ArrayBuffer(byteLength, options?) [ES6]

new ArrayBuffer(
  byteLength: number,
  options?: { // ES2024
    maxByteLength?: number
  }
)

Invoking this constructor via new creates an instance whose capacity is length bytes. Each of those bytes is initially 0.

If options.maxByteLength is provided, the ArrayBuffer can be resized. Otherwise, it has a fixed length.


View API entry online
ArrayBuffer.isView()

ArrayBuffer.isView(arg) [ES6]

Returns true if arg is a view for an ArrayBuffer (i.e., if it is a Typed Array or a DataView).

> ArrayBuffer.isView(new Uint8Array())
true
> ArrayBuffer.isView(new DataView(new ArrayBuffer()))
true

View API entry online
get ArrayBuffer.prototype.byteLength

get ArrayBuffer.prototype.byteLength [ES6]

Returns the capacity of this ArrayBuffer in bytes.


View API entry online
ArrayBuffer.prototype.slice()

ArrayBuffer.prototype.slice(startIndex=0, endIndex=this.byteLength) [ES6]

Creates a new ArrayBuffer that contains the bytes of this ArrayBuffer whose indices are greater than or equal to startIndex and less than endIndex. start and endIndex can be negative (see “Quick references: indices vs. offsets”).


View API entry online
ArrayBuffer.prototype.resize()

ArrayBuffer.prototype.resize(newByteLength) [ES2024]

Changes the size of this ArrayBuffer. For more information, see “Resizing ArrayBuffers 2024.


View API entry online
get ArrayBuffer.prototype.resizable

get ArrayBuffer.prototype.resizable [ES2024]

Returns true if this ArrayBuffer is resizable and false if it is not.


View API entry online
get ArrayBuffer.prototype.maxByteLength

get ArrayBuffer.prototype.maxByteLength [ES2024]

Returns options.maxByteLength if it was provided to the constructor. Otherwise, it returns this.byteLength.


View API entry online
TypedArray.from()

TypedArray.from(iterableOrArrayLike, mapFunc?) [ES6]

// BigInt64Array: bigint instead of number
TypedArray.from<T>(
  iterableOrArrayLike: Iterable<number> | ArrayLike<number>
): TypedArray<T>
TypedArray.from<S, T>(
  iterableOrArrayLike: Iterable<S> | ArrayLike<S>,
  mapFunc: (v: S, k: number) => T, thisArg?: any
): TypedArray<T>

Converts an iterable (including Arrays and Typed Arrays) or an Array-like object to an instance of the Typed Array class.

assert.deepEqual(
  Uint16Array.from([0, 1, 2]),
  Uint16Array.of(0, 1, 2));

The optional mapFunc lets us transform the elements of source before they become elements of the result.

assert.deepEqual(
  Int16Array.from(Int8Array.of(127, 126, 125), x => x * 2),
  Int16Array.of(254, 252, 250));

View API entry online
TypedArray.of()

TypedArray.of(...items) [ES6]

// BigInt64Array: bigint instead of number
TypedArray.of<T>(
  ...items: Array<number>
): TypedArray<T>

Creates a new instance of the Typed Array class whose elements are items (coerced to the element type).

assert.deepEqual(
  Int16Array.of(-1234, 5, 67),
  new Int16Array([-1234, 5, 67]) );

View API entry online
get TypedArray.prototype.buffer

get TypedArray.prototype.buffer [ES6]

Returns the ArrayBuffer backing this Typed Array.


View API entry online
get TypedArray.prototype.length

get TypedArray.prototype.length [ES6]

Returns the length in elements of this Typed Array’s buffer.

> new Uint32Array(new ArrayBuffer(4)).length
1

View API entry online
get TypedArray.prototype.byteLength

get TypedArray.prototype.byteLength [ES6]

Returns the size in bytes of this Typed Array’s buffer.

> new Uint32Array(new ArrayBuffer(4)).byteLength
4

View API entry online
get TypedArray.prototype.byteOffset

get TypedArray.prototype.byteOffset [ES6]

Returns the offset where this Typed Array “starts” inside its ArrayBuffer.


View API entry online
TypedArray.prototype.set()

TypedArray.prototype.set(typedArrayOrArrayLike, offset=0) [ES6]

Copies all elements of the first parameter to this Typed Array. The element at index 0 of the parameter is written to index offset of this Typed Array (etc.). For more information on Array-like objects, see “Array-like objects”.


View API entry online
TypedArray.prototype.subarray()

TypedArray.prototype.subarray(startIndex=0, endIndex=this.length) [ES6]

Returns a new Typed Array that has the same buffer as this Typed Array, but a (generally) smaller range. If startIndex is non-negative then the first element of the resulting Typed Array is this[startIndex], the second this[startIndex+1] (etc.). If startIndex in negative, it is converted appropriately.


View API entry online
new DataView()

new DataView(arrayBuffer, byteOffset?, byteLength?) [ES6]

Creates a new DataView whose data is stored in the ArrayBuffer buffer. By default, the new DataView can access all of buffer. The last two parameters allow us to change that.


View API entry online
get DataView.prototype.buffer

get DataView.prototype.buffer [ES6]

Returns the ArrayBuffer of this DataView.


View API entry online
get DataView.prototype.byteLength

get DataView.prototype.byteLength [ES6]

Returns how many bytes can be accessed by this DataView.


View API entry online
get DataView.prototype.byteOffset

get DataView.prototype.byteOffset [ES6]

Returns at which offset this DataView starts accessing the bytes in its buffer.


View API entry online
DataView.prototype.get()

DataView.prototype.get«ElementType»(byteOffset, littleEndian=false) [ES6]

Returns:

Reads a value from the buffer of this DataView.


View API entry online
DataView.prototype.set()

DataView.prototype.set«ElementType»(byteOffset, value, littleEndian=false) [ES6]

Type of value:

Writes value to the buffer of this DataView.


View API entry online
new Map()

new Map(entries?) [ES6]

new Map<K, V>(
  entries?: Iterable<[K, V]>
)

If we don’t provide the parameter entries, then an empty Map is created. If we do provide an iterable over [key, value] pairs, then those pairs are added as entries to the Map. For example:

const map = new Map([
  [ 1, 'one' ],
  [ 2, 'two' ],
  [ 3, 'three' ], // trailing comma is ignored
]);

View API entry online
Map.groupBy()

Map.groupBy(items, computeGroupKey) [ES2024]

Map.groupBy<K, T>(
  items: Iterable<T>,
  computeGroupKey: (item: T, index: number) => K,
): Map<K, Array<T>>;
assert.deepEqual(
  Map.groupBy(
    ['orange', 'apricot', 'banana', 'apple', 'blueberry'],
    (str) => str[0] // compute group key
  ),
  new Map()
    .set('o', ['orange'])
    .set('a', ['apricot', 'apple'])
    .set('b', ['banana', 'blueberry'])
);

View API entry online
Map.prototype.get()

Map.prototype.get(key) [ES6]

Returns the value that key is mapped to in this Map. If there is no key key in this Map, undefined is returned.

const map = new Map([[1, 'one'], [2, 'two']]);
assert.equal(map.get(1), 'one');
assert.equal(map.get(5), undefined);

View API entry online
Map.prototype.set()

Map.prototype.set(key, value) [ES6]

const map = new Map([[1, 'one'], [2, 'two']]);
map.set(1, 'ONE!') // update an existing entry
   .set(3, 'THREE!') // create a new entry
;
assert.deepEqual(
  Array.from(map.entries()),
  [[1, 'ONE!'], [2, 'two'], [3, 'THREE!']]
);

View API entry online
Map.prototype.has()

Map.prototype.has(key) [ES6]

Returns whether the given key exists in this Map.

const map = new Map([[1, 'one'], [2, 'two']]);
assert.equal(map.has(1), true); // key exists
assert.equal(map.has(5), false); // key does not exist

View API entry online
Map.prototype.delete()

Map.prototype.delete(key) [ES6]

If there is an entry whose key is key, it is removed and true is returned. Otherwise, nothing happens and false is returned.

const map = new Map([[1, 'one'], [2, 'two']]);
assert.equal(map.delete(1), true);
assert.equal(map.delete(5), false); // nothing happens
assert.deepEqual(
  Array.from(map.entries()),
  [[2, 'two']]
);

View API entry online
get Map.prototype.size

get Map.prototype.size [ES6]

Returns how many entries this Map has.

const map = new Map([[1, 'one'], [2, 'two']]);
assert.equal(map.size, 2);

View API entry online
Map.prototype.clear()

Map.prototype.clear() [ES6]

Removes all entries from this Map.

const map = new Map([[1, 'one'], [2, 'two']]);
assert.equal(map.size, 2);
map.clear();
assert.equal(map.size, 0);

View API entry online
Map.prototype.entries()

Map.prototype.entries() [ES6]

Returns an iterable with one [key, value] pair for each entry in this Map. The pairs are Arrays of length 2.

const map = new Map([[1, 'one'], [2, 'two']]);
for (const entry of map.entries()) {
  console.log(entry);
}

Output:

[ 1, 'one' ]
[ 2, 'two' ]

View API entry online
Map.prototype.forEach()

Map.prototype.forEach(callback, thisArg?) [ES6]

Map.prototype.forEach(
  callback: (value: V, key: K, theMap: Map<K,V>) => void,
  thisArg?: any
): void
const map = new Map([[1, 'one'], [2, 'two']]);
map.forEach((value, key) => console.log(value, key));

Output:

one 1
two 2

View API entry online
Map.prototype.keys()

Map.prototype.keys() [ES6]

Returns an iterable over all keys in this Map.

const map = new Map([[1, 'one'], [2, 'two']]);
for (const key of map.keys()) {
  console.log(key);
}

Output:

1
2

View API entry online
Map.prototype.values()

Map.prototype.values() [ES6]

Returns an iterable over all values in this Map.

const map = new Map([[1, 'one'], [2, 'two']]);
for (const value of map.values()) {
  console.log(value);
}

Output:

one
two

View API entry online
Map.prototype[Symbol.iterator]()

Map.prototype[Symbol.iterator]() [ES6]

The default way of iterating over Maps. Same as map.entries().

const map = new Map([[1, 'one'], [2, 'two']]);
for (const [key, value] of map) {
  console.log(key, value);
}

Output:

1 one
2 two

View API entry online
new Set()

new Set(iterable) [ES6]

const set = new Set(['red', 'green', 'blue']);

View API entry online
Set.prototype.add()

Set.prototype.add(value) [ES6]

const set = new Set(['red']);
set.add('green').add('blue');
assert.deepEqual(
  Array.from(set), ['red', 'green', 'blue']
);

View API entry online
Set.prototype.delete()

Set.prototype.delete(value) [ES6]

const set = new Set(['red', 'green', 'blue']);
assert.equal(set.delete('red'), true); // there was a deletion
assert.deepEqual(
  Array.from(set), ['green', 'blue']
);

View API entry online
Set.prototype.has()

Set.prototype.has(value) [ES6]

Returns true if value is in this Set and false otherwise.

const set = new Set(['red', 'green']);
assert.equal(set.has('red'), true);
assert.equal(set.has('blue'), false);

View API entry online
get Set.prototype.size

get Set.prototype.size [ES6]

Returns how many elements there are in this Set.

const set = new Set(['red', 'green', 'blue']);
assert.equal(set.size, 3);

View API entry online
Set.prototype.clear()

Set.prototype.clear() [ES6]

Removes all elements from this Set.

const set = new Set(['red', 'green', 'blue']);
assert.equal(set.size, 3);
set.clear();
assert.equal(set.size, 0);

View API entry online
Set.prototype.values()

Set.prototype.values() [ES6]

Returns an iterable over all elements of this Set.

const set = new Set(['red', 'green']);
for (const x of set.values()) {
  console.log(x);
}

Output:

red
green

View API entry online
Set.prototype[Symbol.iterator]()

Set.prototype[Symbol.iterator]() [ES6]

Default way of iterating over Sets. Same as .values().

const set = new Set(['red', 'green']);
for (const x of set) {
  console.log(x);
}

Output:

red
green

View API entry online
Set.prototype.forEach()

Set.prototype.forEach(callback, thisArg?) [ES6]

forEach(
  callback: (value: T, key: T, theSet: Set<T>) => void,
  thisArg?: any
): void

Feeds each element of this Set to callback(). value and key both contain the current element. This redundancy was introduced so that this callback has the same type signature as the callback of Map.prototype.forEach().

We can specify the this of callback via thisArg. If we omit it, this is undefined.

const set = new Set(['red', 'green']);
set.forEach(x => console.log(x));

Output:

red
green

View API entry online
Set.prototype.entries()

Set.prototype.entries(): Iterable<[T,T]> [ES6]

Mainly exists so that Sets and Maps have similar interfaces: Each Set element is viewed as a key-value entry whose key and value are both that element:

> new Set(['a', 'b', 'c']).entries().toArray()
[ [ 'a', 'a' ], [ 'b', 'b' ], [ 'c', 'c' ] ]

.entries() enables us to convert a Set to a Map:

const set = new Set(['a', 'b', 'c']);
const map = new Map(set.entries());
assert.deepEqual(
  Array.from(map.entries()),
  [['a','a'], ['b','b'], ['c','c']]
);

View API entry online
Set.prototype.keys()

Set.prototype.keys(): Iterable<T> [ES6]

Mainly exists so that Sets and Maps have similar interfaces: Each Set element is viewed as a key-value entry whose key and value are both that element. Therefore the result of .keys() is the same as the result of .values():

> new Set(['a', 'b', 'c']).keys().toArray()
[ 'a', 'b', 'c' ]

View API entry online
Set.prototype.union()

Set.prototype.union(other) [ES2025]

Set<T>.prototype.union(other: SetLike<T>): Set<T>

This method returns a Set that is the union of this and other. It contains a value if it is in this or other.

assert.deepEqual(
  new Set(['a', 'b']).union(new Set(['b', 'c'])),
  new Set(['a', 'b', 'c'])
);

other doesn’t have to be a Set, it only has to be Set-like and have the property .size and the methods .has(key) and .keys(). Sets and Maps both fulfill those requirements.


View API entry online
Set.prototype.intersection()

Set.prototype.intersection(other) [ES2025]

Set<T>.prototype.intersection(other: SetLike<T>): Set<T>

This method returns a Set that is the intersection of this and other. It contains a value if it is in this or other.

assert.deepEqual(
  new Set(['a', 'b']).intersection(new Set(['b', 'c'])),
  new Set(['b'])
);

other doesn’t have to be a Set, it only has to be Set-like and have the property .size and the methods .has(key) and .keys(). Sets and Maps both fulfill those requirements.


View API entry online
Set.prototype.difference()

Set.prototype.difference(other) [ES2025]

Set<T>.prototype.difference(other: SetLike<T>): Set<T>

This method returns a Set that is the difference between this and other. It contains a value if it is in this but not in other.

assert.deepEqual(
  new Set(['a', 'b']).difference(new Set(['b', 'c'])),
  new Set(['a'])
);

other doesn’t have to be a Set, it only has to be Set-like and have the property .size and the methods .has(key) and .keys(). Sets and Maps both fulfill those requirements.


View API entry online
Set.prototype.symmetricDifference()

Set.prototype.symmetricDifference(other) [ES2025]

Set<T>.prototype.symmetricDifference(other: SetLike<T>): Set<T>

This method returns a Set that is the symmetric difference between this and other. It contains a value if it is only in this or only in other.

assert.deepEqual(
  new Set(['a', 'b']).symmetricDifference(new Set(['b', 'c'])),
  new Set(['a', 'c'])
);

other doesn’t have to be a Set, it only has to be Set-like and have the property .size and the methods .has(key) and .keys(). Sets and Maps both fulfill those requirements.

For more information on this method, see its section in this chapter.


View API entry online
Set.prototype.isSubsetOf()

Set.prototype.isSubsetOf(other) [ES2025]

Set<T>.prototype.isSubsetOf(other: SetLike<T>): boolean

Returns true if all elements of this are in other:

assert.deepEqual(
  new Set(['a', 'b']).isSubsetOf(new Set(['a', 'b', 'c'])),
  true
);

View API entry online
Set.prototype.isSupersetOf()

Set.prototype.isSupersetOf(other) [ES2025]

Set<T>.prototype.isSupersetOf(other: SetLike<T>): boolean

Returns true if this contains all elements of other:

assert.deepEqual(
  new Set(['a', 'b', 'c']).isSupersetOf(new Set(['a', 'b'])),
  true
);

View API entry online
Set.prototype.isDisjointFrom()

Set.prototype.isDisjointFrom(other) [ES2025]

Set<T>.prototype.isDisjointFrom(other: SetLike<T>): boolean

Returns true if this and other have no elements in common:

assert.deepEqual(
  new Set(['a', 'b', 'c']).isDisjointFrom(new Set(['x'])),
  true
);

View API entry online
new Promise()

new Promise(executor) [ES6]

new Promise<T>(
  executor: (
    resolve: (value: T | PromiseLike<T>) => void,
    reject: (reason?: any) => void
  ) => void
): Promise<T>

This constructor creates a new Promise. It passes functions to its callback with which that Promise can be resolved or rejected:

// Create a Promise and resolve it
new Promise((resolve, reject) => {
  resolve('Result');
}).then((value) => {
  assert.equal(value, 'Result');
});

// Create a Promise and reject it
new Promise((resolve, reject) => {
  reject('Error');
}).catch((reason) => {
  assert.equal(reason, 'Error');
});

View API entry online
Promise.withResolvers()

Promise.withResolvers() [ES2024]

Promise.withResolvers<T>(): PromiseWithResolvers<T>;
interface PromiseWithResolvers<T> {
  promise: Promise<T>;
  resolve: (value: T | PromiseLike<T>) => void;
  reject: (reason?: any) => void;
}

This method creates a Promise and returns an object that contains that Promise plus functions for resolving or rejecting it.


View API entry online
Promise.resolve()

Promise.resolve(value?) [ES6]

Creates a Promise, resolves it with value and returns it:

Promise.resolve('Yes')
.then((value) => {
  assert.equal(value, 'Yes');
});

View API entry online
Promise.reject()

Promise.reject(reason?) [ES6]

Creates a Promise, rejects it with value and returns it:

Promise.reject('No')
.catch((reason) => {
  assert.equal(reason, 'No');
});

View API entry online
Promise.try()

Promise.try(callback, ...args) [ES2025]

Creates a Promise by treating callback as if it were a .then() callback:

The use case for this method is starting a Promise chain with code that is not purely asynchronous – e.g.:

function computeAsync() {
  return Promise.try(() => {
    const value = syncFuncMightThrow();
    return asyncFunc(value);
  });
}

View API entry online
Promise.all()

Promise.all(promises) [ES6]

Promise.all<T>(
  promises: Iterable<Promise<T>>
): Promise<Array<T>>

View API entry online
Promise.race()

Promise.race(promises) [ES6]

Promise.race<T>(
  promises: Iterable<Promise<T>>
): Promise<T>

View API entry online
Promise.any()

Promise.any(promises) [ES2021]

Promise.any<T>(
  promises: Iterable<Promise<T>>
): Promise<T>

This is the type signature of AggregateError (a few members were omitted):

class AggregateError {
  constructor(errors: Iterable<any>, message: string);
  get errors(): Array<any>;
  get message(): string;
}

View API entry online
Promise.allSettled()

Promise.allSettled(promises) [ES2020]

Promise.allSettled<T>(
  promises: Iterable<Promise<T>>
): Promise<Array<SettlementObject<T>>>

This is the type signature of SettlementObject:

type SettlementObject<T> = FulfillmentObject<T> | RejectionObject;

interface FulfillmentObject<T> {
  status: 'fulfilled';
  value: T;
}

interface RejectionObject {
  status: 'rejected';
  reason: unknown;
}

View API entry online
Promise.prototype.then()

Promise.prototype.then(onFulfilled?, onRejected?) [ES6]

interface Promise<T> {
  then<TResult1, TResult2>(
    onFulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>,
    onRejected?: (reason: any) => TResult2 | PromiseLike<TResult2>
  ): Promise<TResult1 | TResult2>;
}

Registers callbacks for the fulfillment value and/or the rejection value of a Promise. Usually, only the first parameter onFulfilled is used. .catch() provides a more self-descriptive alternative to using the second parameter onRejected.

Promise.resolve('Yes')
.then((value) => {
  assert.equal(value, 'Yes');
});

View API entry online
Promise.prototype.catch()

Promise.prototype.catch(onRejected) [ES6]

interface Promise<T> {
  catch<TResult>(
    onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>
  ): Promise<T | TResult>;
}

Registers a callback for the rejection value of a Promise. A more self-descriptive alternative to using .then() for that purpose – the following two invocations are equivalent:

promise.catch(onRejected)
promise.then(undefined, onRejected)

Example:

Promise.reject('No')
.catch((reason) => {
  assert.equal(reason, 'No');
});

View API entry online
Promise.prototype.finally()

Promise.prototype.finally(onFinally) [ES2018]

interface Promise<T> {
  // Returning a rejected Promise from onFinally does have an effect!
  finally(onFinally?: () => void);
}

Often used as follows:

somePromise
  .then((result) => {
    // ···
  })
  .catch((error) => {
    // ···
  })
  .finally(() => {
    // ···
  })
;

The .finally() callback is always executed – independently of somePromise and the values returned by .then() and/or .catch(). The callback only has an effect if it returns a rejected Promise or throws an exception. Then the final Promise is rejected with the rejection value or the exception.


View API entry online
String.prototype.match()

String.prototype.match(regExpOrString) [ES3 | /y honors and updates .lastIndex | /g /gy ignore and reset .lastIndex ]


View API entry online
String.prototype.matchAll()

String.prototype.matchAll(regExp) [ES2020 | /g /gy honor and preserve .lastIndex]

matchAll(regexp: RegExp): Iterator<RegExpExecArray>
interface RegExpMatchArray extends Array<string> {
  index: number;
  input: string;
  groups: undefined | {
    [key: string]: string
  };
}

Example:

> 'yes'.matchAll(/(y|s)/gv).toArray()
[
  { 0: 'y', 1: 'y', index: 0, input: 'yes', groups: undefined },
  { 0: 's', 1: 's', index: 2, input: 'yes', groups: undefined },
]

View API entry online
String.prototype.search()

String.prototype.search(regExpOrString) [ES3 | Ignores .lastIndex]

Returns the index at which regExpOrString occurs within the string. If regExpOrString is a string, it is used to create a regular expression (think parameter of new RegExp()).

> 'a2b'.search(/[0-9]/)
1
> 'a2b'.search('[0-9]')
1

View API entry online
String.prototype.split()

String.prototype.split(separator, limit?) [ES3 | Ignores .lastIndex]

split(separator: string | RegExp, limit?: number): Array<string>

The separator can be a string (which is interpreted as plain text, not as a regular expression pattern) or a regular expression.

Examples:

// Splitting with a string
assert.deepEqual(
  'a.b.c'.split('.'),
  [ 'a', 'b', 'c' ]
);

// Splitting with a regular expression
assert.deepEqual(
  'a x:yyy b'.split(/x+:y+/),
  [ 'a ', ' b' ]
);

// Group captures appear in the result
assert.deepEqual(
  'a x:yyy b'.split(/(x+):(y+)/),
  [ 'a ', 'x', 'yyy', ' b' ]
);

If we want the separators to be part of the returned string fragments, we can use a regular expression with a lookbehind assertion or a lookahead assertion:

> 'a: b: c'.split(/(?<=:) */)
[ 'a:', 'b:', 'c' ]
> 'a :b :c'.split(/ *(?=:)/)
[ 'a', ':b', ':c' ]

Pitfall: .split('') splits into JavaScript characters, but we usually want to split into grapheme clusters or at least Unicode code points. Therefore, it’s better to use Array.from() or Intl.Segmenter for splitting. For more information, see “Atoms of text: code points, JavaScript characters, grapheme clusters”.


View API entry online
String.prototype.replace()

String.prototype.replace(searchValue, replaceValue) [ES3 | /y honors and updates .lastIndex | /g /gy ignore and reset .lastIndex]

For more information on this method, see its section earlier in this chapter.


View API entry online
String.prototype.replaceAll()

String.prototype.replaceAll(searchValue, replaceValue) [ES2021 | /g /gy ignore and reset .lastIndex]


View API entry online
RegExp.prototype.test()

RegExp.prototype.test(string) [ES3 | /g /y /gy honor and update .lastIndex]

test(string: string): boolean

Returns true if the receiver matches string:

> /^# /.test('# comment')
true
> /^# /.test('#comment')
false
> /^# /.test('abc')
false

Pitfall: Don’t use this method with a regular expression that has flag /g. Then regExp.test() starts matching at regExp.lastIndex and also updates that property.


View API entry online
RegExp.prototype.exec()

RegExp.prototype.exec(string) [ES3 | /g /y /gy honor and update .lastIndex]


View API entry online