Number of cards:
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.
Number.MAX_VALUE()
Number.MAX_VALUE
[ES1]
The largest positive finite JavaScript number.
Number.MIN_VALUE()
Number.MIN_VALUE
[ES1]
The smallest positive JavaScript number. Approximately 5 × 10−324.
Number.NEGATIVE_INFINITY()
Number.NEGATIVE_INFINITY
[ES1]
The same as -Number.POSITIVE_INFINITY
.
Number.POSITIVE_INFINITY()
Number.POSITIVE_INFINITY
[ES1]
The same as the global variable Infinity
.
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
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
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
Number.prototype.toExponential()
Number.prototype.toExponential(fractionDigits?)
[ES3]
fractionDigits
, we can specify, how many digits should be shown of the number that is multiplied with the exponent.
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'
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'
Number.prototype.toPrecision()
Number.prototype.toPrecision(precision?)
[ES3]
.toString()
, but precision
specifies how many digits should be shown overall.
precision
is missing, .toString()
is used.
> 1234..toPrecision(3) // requires exponential notation
'1.23e+3'
> 1234..toPrecision(4)
'1234'
> 1234..toPrecision(5)
'1234.0'
> 1.234.toPrecision(3)
'1.23'
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
Number.MIN_SAFE_INTEGER()
Number.MIN_SAFE_INTEGER
[ES6]
The smallest integer that JavaScript can represent unambiguously (−253+1).
Number.MAX_SAFE_INTEGER()
Number.MAX_SAFE_INTEGER
[ES6]
The largest integer that JavaScript can represent unambiguously (253−1).
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
Number.isSafeInteger()
Number.isSafeInteger(num)
[ES6]
Returns true
if num
is a number and unambiguously represents an integer.
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
Math.E()
Math.E: number
[ES1]
Euler’s number, base of the natural logarithms, approximately 2.7182818284590452354.
Math.LN10()
Math.LN10: number
[ES1]
The natural logarithm of 10, approximately 2.302585092994046.
Math.LN2()
Math.LN2: number
[ES1]
The natural logarithm of 2, approximately 0.6931471805599453.
Math.LOG10E()
Math.LOG10E: number
[ES1]
The logarithm of e to base 10, approximately 0.4342944819032518.
Math.LOG2E()
Math.LOG2E: number
[ES1]
The logarithm of e to base 2, approximately 1.4426950408889634.
Math.PI()
Math.PI: number
[ES1]
The mathematical constant π, ratio of a circle’s circumference to its diameter, approximately 3.1415926535897932.
Math.SQRT1_2()
Math.SQRT1_2: number
[ES1]
The square root of 1/2, approximately 0.7071067811865476.
Math.SQRT2()
Math.SQRT2: number
[ES1]
The square root of 2, approximately 1.4142135623730951.
Math.cbrt()
Math.cbrt(x: number): number
[ES6]
Returns the cube root of x
.
> Math.cbrt(8)
2
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
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.
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
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.
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
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
Math.pow()
Math.pow(x: number, y: number): number
[ES1]
Returns x
y
, x
to the power of y
. The same as x ** y
.
> Math.pow(2, 3)
8
> Math.pow(25, 0.5)
5
Math.sqrt()
Math.sqrt(x: number): number
[ES1]
Returns the square root of x
. The inverse of x ** 2
.
> Math.sqrt(9)
3
Math.ceil()
Math.ceil(x: number): number
[ES1]
Returns the smallest (closest to −∞) integer i
with x
≤ i
.
> Math.ceil(2.1)
3
> Math.ceil(2.9)
3
Math.floor()
Math.floor(x: number): number
[ES1]
Returns the largest (closest to +∞) integer i
with i
≤ x
.
> Math.floor(2.1)
2
> Math.floor(2.9)
2
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
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
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
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
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
Math.acosh()
Math.acosh(x: number): number
[ES6]
Returns the inverse hyperbolic cosine of x
.
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
Math.asinh()
Math.asinh(x: number): number
[ES6]
Returns the inverse hyperbolic sine of x
.
Math.atan()
Math.atan(x: number): number
[ES1]
Returns the arc tangent (inverse tangent) of x
.
Math.atanh()
Math.atanh(x: number): number
[ES6]
Returns the inverse hyperbolic tangent of x
.
Math.atan2()
Math.atan2(y: number, x: number): number
[ES1]
Returns the arc tangent of the quotient y/x.
Math.cos()
Math.cos(x: number): number
[ES1]
Returns the cosine of x
.
> Math.cos(0)
1
> Math.cos(Math.PI)
-1
Math.cosh()
Math.cosh(x: number): number
[ES6]
Returns the hyperbolic cosine of x
.
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
Math.sin()
Math.sin(x: number): number
[ES1]
Returns the sine of x
.
> Math.sin(0)
0
> Math.sin(Math.PI / 2)
1
Math.sinh()
Math.sinh(x: number): number
[ES6]
Returns the hyperbolic sine of x
.
Math.tan()
Math.tan(x: number): number
[ES1]
Returns the tangent of x
.
> Math.tan(0)
0
> Math.tan(1)
1.5574077246549023
Math.tanh()
Math.tanh(x: number): number;
[ES6]
Returns the hyperbolic tangent of x
.
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
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
Math.max()
Math.max(...values: Array<number>): number
[ES1]
Converts values
to numbers and returns the largest one.
> Math.max(3, -5, 24)
24
Math.min()
Math.min(...values: Array<number>): number
[ES1]
Converts values
to numbers and returns the smallest one.
> Math.min(3, -5, 24)
-5
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);
}
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
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
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
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
String.prototype.indexOf()
String.prototype.indexOf(searchString, minIndex=0)
[ES1]
searchString
appears at minIndex
or after: Return the lowest index where it is found. Otherwise: Return -1
.
> 'aaax'.indexOf('aa', 0)
0
> 'aaax'.indexOf('aa', 1)
1
> 'aaax'.indexOf('aa', 2)
-1
String.prototype.lastIndexOf()
String.prototype.lastIndexOf(searchString, maxIndex?)
[ES1]
searchString
appears at maxIndex
or before: Return the highest index where it is found. Otherwise: Return -1
.
maxIndex
is missing, the search starts at this.length - searchString.length
(assuming that searchString
is shorter than this
).
> 'xaaa'.lastIndexOf('aa', 3)
2
> 'xaaa'.lastIndexOf('aa', 2)
2
> 'xaaa'.lastIndexOf('aa', 1)
1
> 'xaaa'.lastIndexOf('aa', 0)
-1
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'
String.prototype.at()
String.prototype.at(index: number)
[ES2022]
index
as a string.
undefined
.
index
is negative, it is added to .length
before it is used (-1
becomes this.length-1
, etc.).
> 'abc'.at(0)
'a'
> 'abc'.at(-1)
'c'
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.
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'
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'
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#'
String.prototype.repeat()
String.prototype.repeat(count=0)
[ES6]
Returns the string, concatenated count
times.
> '*'.repeat()
''
> '*'.repeat(3)
'***'
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()
'ΑΒΓ'
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()
'αβγ'
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'
String.prototype.trimStart()
String.prototype.trimStart()
[ES2019]
Similar to .trim()
but only the beginning of the string is trimmed:
> ' abc '.trimStart()
'abc '
String.prototype.trimEnd()
String.prototype.trimEnd()
[ES2019]
Similar to .trim()
but only the end of the string is trimmed:
> ' abc '.trimEnd()
' abc'
String.prototype.normalize()
String.prototype.normalize(form = 'NFC')
[ES6]
form
: 'NFC', 'NFD', 'NFKC', 'NFKD'
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
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']
);
Object.create()
Object.create(proto, propDescObj?)
[ES5]
proto
.
propDescObj
is an object with property descriptors that is used to define properties in the new object.
> 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',
}
);
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
);
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
);
Object.defineProperty()
Object.defineProperty(obj, propKey, propDesc)
[ES5]
obj
, as specified by the property key propKey
and the property descriptor propDesc
.
obj
.
const obj = {};
Object.defineProperty(
obj, 'color',
{
value: 'green',
writable: true,
enumerable: true,
configurable: true,
}
);
assert.deepEqual(
obj,
{
color: 'green',
}
);
Object.defineProperties()
Object.defineProperties(obj, propDescObj)
[ES5]
obj
, as specified by the object propDescObj
with property descriptors.
obj
.
const obj = {};
Object.defineProperties(
obj,
{
color: {
value: 'green',
writable: true,
enumerable: true,
configurable: true,
},
}
);
assert.deepEqual(
obj,
{
color: 'green',
}
);
Object.getOwnPropertyDescriptor()
Object.getOwnPropertyDescriptor(obj, propKey)
[ES5]
obj
whose key is propKey
. If no such property exists, it returns undefined
.
> Object.getOwnPropertyDescriptor({a: 1, b: 2}, 'a')
{ value: 1, writable: true, enumerable: true, configurable: true }
> Object.getOwnPropertyDescriptor({a: 1, b: 2}, 'x')
undefined
Object.getOwnPropertyDescriptors()
Object.getOwnPropertyDescriptors(obj)
[ES2017]
obj
.
> Object.getOwnPropertyDescriptors({a: 1, b: 2})
{
a: { value: 1, writable: true, enumerable: true, configurable: true },
b: { value: 2, writable: true, enumerable: true, configurable: true },
}
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']
);
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']
);
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]
);
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 ]
Object.entries()
Object.entries(obj)
[ES2017]
obj
.
Object.fromEntries()
const obj = {
a: 1,
b: 2,
[Symbol('myKey')]: 3,
};
assert.deepEqual(
Object.entries(obj),
[
['a', 1],
['b', 2],
// Property with symbol key is ignored
]
);
Object.fromEntries()
Object.fromEntries(keyValueIterable)
[ES2019]
keyValueIterable
.
Object.entries()
> Object.fromEntries([['a', 1], ['b', 2]])
{ a: 1, b: 2 }
Object.hasOwn()
Object.hasOwn(obj, key)
[ES2022]
true
if obj
has an own property whose key is key
. If not, it returns false
.
> Object.hasOwn({a: 1, b: 2}, 'a')
true
> Object.hasOwn({a: 1, b: 2}, 'x')
false
Object.preventExtensions()
Object.preventExtensions(obj)
[ES5]
obj
non-extensible and returns it.
obj
is non-extensible: We can’t add properties or change its prototype.
obj
is changed (shallow change). Nested objects are not affected.
Object.isExtensible()
Object.isExtensible()
Object.isExtensible(obj)
[ES5]
true
if obj
is extensible and false
if it isn’t.
Object.preventExtensions()
Object.seal()
Object.seal(obj)
[ES5]
obj
and returns it.
obj
is non-extensible: We can’t add properties or change its prototype.
obj
is sealed: Additionally, all of its properties are unconfigurable.
obj
is changed (shallow change). Nested objects are not affected.
Object.isSealed()
Object.isSealed()
Object.isSealed(obj)
[ES5]
true
if obj
is sealed and false
if it isn’t.
Object.seal()
Object.freeze()
Object.freeze(obj)
[ES5]
obj
and returns it.
obj
is non-extensible: We can’t add properties or change its prototype.
obj
is sealed: Additionally, all of its properties are unconfigurable.
obj
is frozen: Additionally, all of its properties are non-writable.
obj
is changed (shallow change). Nested objects are not affected.
Object.isFrozen()
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'/,
}
);
Object.isFrozen()
Object.isFrozen(obj)
[ES5]
true
if obj
is frozen.
Object.freeze()
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 }
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>}
computeGroupKey
returns a group key for each of the items
.
Object.groupBy()
is an object where:
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'],
}
);
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
NaN
values to be equal can be useful – e.g., when searching for a value in an Array.
-0
is rare and it’s usually best to pretend it is the same as 0
.
Reflect.apply()
Reflect.apply(target, thisArgument, argumentsList)
[ES6]
target
with the arguments provided by argumentsList
and this
set to thisArgument
.
target.apply(thisArgument, argumentsList)
Reflect.construct()
Reflect.construct(target, argumentsList, newTarget=target)
[ES6]
new
operator as a function.
target
is the constructor to invoke.
newTarget
points to the constructor that started the current chain of constructor calls.
Reflect.defineProperty()
Reflect.defineProperty(target, propertyKey, propDesc)
[ES6]
Object.defineProperty()
.
Reflect.deleteProperty()
Reflect.deleteProperty(target, propertyKey)
[ES6]
The delete
operator as a function. It works slightly differently, though:
true
if it successfully deleted the property or if the property never existed.
false
if the property could not be deleted and still exists.
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.
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
.
Reflect.getOwnPropertyDescriptor()
Reflect.getOwnPropertyDescriptor(target, propertyKey)
[ES6]
Same as Object.getOwnPropertyDescriptor()
.
Reflect.getPrototypeOf()
Reflect.getPrototypeOf(target)
[ES6]
Same as Object.getPrototypeOf()
.
Reflect.has()
Reflect.has(target, propertyKey)
[ES6]
The in
operator as a function.
Reflect.isExtensible()
Reflect.isExtensible(target)
[ES6]
Same as Object.isExtensible()
.
Reflect.ownKeys()
Reflect.ownKeys(target)
[ES6]
Returns all own property keys (strings and symbols) in an Array.
Reflect.preventExtensions()
Reflect.preventExtensions(target)
[ES6]
Object.preventExtensions()
.
Reflect.set()
Reflect.set(target, propertyKey, value, receiver=target)
[ES6]
Reflect.setPrototypeOf()
Reflect.setPrototypeOf(target, proto)
[ES6]
Object.setPrototypeOf()
.
Object.prototype.toString()
Object.prototype.toString()
[ES1]
Configures how an object is converted to a string.
> 'Object: ' + {toString() {return 'Hello!'}}
'Object: Hello!'
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.
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
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
);
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
get Object.prototype.__proto__
get Object.prototype.__proto__
[ES6]
Avoid:
Object.getPrototypeOf()
.
set Object.prototype.__proto__
set Object.prototype.__proto__
[ES6]
Avoid:
Object.setPrototypeOf()
.
Object.prototype.hasOwnProperty()
Object.prototype.hasOwnProperty
[ES3]
Avoid:
Object.hasOwn()
2022
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']
);
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']
);
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”.
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']
);
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']
);
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
);
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
);
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'
);
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”.
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']
);
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']
);
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), [,,,]);
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>
mapFunc
before they are added to the output Array.
Examples:
> Array.from(new Set(['a', 'b'])) // iterable
[ 'a', 'b' ]
> Array.from({length: 2, 0:'a', 1:'b'}) // Array-like object
[ 'a', 'b' ]
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
);
Array.prototype.at()
Array.prototype.at(index)
[ES2022 | Non-mutating]
index
. If there is no such element, it returns undefined
.
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'
Array.prototype.with()
Array.prototype.with(index, value)
[ES2023 | Non-mutating]
index
, there is now value
.
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' ]
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.
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 ]
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' ]
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' ] ]
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' ]
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' ]
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' ]
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' ]
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' ]
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();
Array.prototype.splice()
Array.prototype.splice(start?, deleteCount?, ...items)
[ES3 | Mutating]
start
,
deleteCount
elements (default: all remaining elements) and
items
.
.toSpliced()
.
> 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' ]
Array.prototype.toSpliced()
Array.prototype.toSpliced(start?, deleteCount?, ...items)
[ES2023 | Non-mutating]
start
, deleteCount
elements are replaced with items
.
deleteCount
is missing, all elements from start
until the end are deleted.
.splice()
.
> 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' ]
Array.prototype.fill()
Array.prototype.fill(start=0, end=this.length)
[ES6 | Mutating]
this
.
value
to every index between (including) start
and (excluding) end
.
> [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()
.
Array.prototype.copyWithin()
Array.prototype.copyWithin(target, start, end=this.length)
[ES6 | Mutating]
this
.
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.
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
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
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
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
predicate
returns a truthy value.
undefined
.
> [-1, 2, -3].find(x => x < 0)
-1
> [1, 2, 3].find(x => x < 0)
undefined
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
predicate
returns a truthy value.
undefined
.
> [-1, 2, -3].findLast(x => x < 0)
-3
> [1, 2, 3].findLast(x => x < 0)
undefined
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
predicate
returns a truthy value.
-1
.
> [-1, 2, -3].findIndex(x => x < 0)
0
> [1, 2, 3].findIndex(x => x < 0)
-1
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
predicate
returns a truthy value.
-1
.
> [-1, 2, -3].findLastIndex(x => x < 0)
2
> [1, 2, 3].findLastIndex(x => x < 0)
-1
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 ]
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 ]
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 => [])
[]
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]
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
false
).
.some()
(“exists”).
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
true
).
.every()
(“for all”).
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.
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'
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'
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()
''
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.
Array.prototype.sort()
Array.prototype.sort(compareFunc?)
[ES1 | Mutating]
Array<T>.prototype.sort(
compareFunc?: (a: T, b: T) => number
): this
.toSorted()
.
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']
);
Array.prototype.toSorted()
Array.prototype.toSorted(compareFunc?)
[ES2023 | Non-mutating]
Array<T>.prototype.toSorted.toSorted(
compareFunc?: (a: T, b: T) => number
): Array<T>
.sort()
.
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.
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()
.
Array.prototype.toReversed()
Array.prototype.toReversed()
[ES2023 | Non-mutating]
.reverse()
.
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']
);
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.
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
get ArrayBuffer.prototype.byteLength
get ArrayBuffer.prototype.byteLength
[ES6]
Returns the capacity of this ArrayBuffer in bytes.
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”).
ArrayBuffer.prototype.resize()
ArrayBuffer.prototype.resize(newByteLength)
[ES2024]
Changes the size of this ArrayBuffer. For more information, see “Resizing ArrayBuffers 2024”.
get ArrayBuffer.prototype.resizable
get ArrayBuffer.prototype.resizable
[ES2024]
Returns true
if this ArrayBuffer is resizable and false
if it is not.
get ArrayBuffer.prototype.maxByteLength
get ArrayBuffer.prototype.maxByteLength
[ES2024]
Returns options.maxByteLength
if it was provided to the constructor. Otherwise, it returns this.byteLength
.
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));
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]) );
get TypedArray.prototype.buffer
get TypedArray.prototype.buffer
[ES6]
Returns the ArrayBuffer backing this Typed Array.
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
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
get TypedArray.prototype.byteOffset
get TypedArray.prototype.byteOffset
[ES6]
Returns the offset where this Typed Array “starts” inside its ArrayBuffer.
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”.
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.
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.
get DataView.prototype.buffer
get DataView.prototype.buffer
[ES6]
Returns the ArrayBuffer of this DataView.
get DataView.prototype.byteLength
get DataView.prototype.byteLength
[ES6]
Returns how many bytes can be accessed by this DataView.
get DataView.prototype.byteOffset
get DataView.prototype.byteOffset
[ES6]
Returns at which offset this DataView starts accessing the bytes in its buffer.
DataView.prototype.get()
DataView.prototype.get«ElementType»(byteOffset, littleEndian=false)
[ES6]
Returns:
BigInt64
, BigUint64
: bigint
number
Reads a value from the buffer of this DataView.
DataView.prototype.set()
DataView.prototype.set«ElementType»(byteOffset, value, littleEndian=false)
[ES6]
Type of value
:
BigInt64
, BigUint64
: bigint
number
Writes value
to the buffer of this DataView.
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
]);
Map.groupBy()
Map.groupBy(items, computeGroupKey)
[ES2024]
Map.groupBy<K, T>(
items: Iterable<T>,
computeGroupKey: (item: T, index: number) => K,
): Map<K, Array<T>>;
computeGroupKey
returns a group key for each of the items
.
Map.groupBy()
is a Map where:
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'])
);
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);
Map.prototype.set()
Map.prototype.set(key, value)
[ES6]
key
, it is updated. Otherwise, a new entry is created.
this
, which means that we can chain it.
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!']]
);
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
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']]
);
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);
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);
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' ]
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
thisArg
is provided, this
is set to it for each invocation. Otherwise, this
is set to undefined
.
const map = new Map([[1, 'one'], [2, 'two']]);
map.forEach((value, key) => console.log(value, key));
Output:
one 1
two 2
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
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
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
new Set()
new Set(iterable)
[ES6]
values
, then an empty Set is created.
const set = new Set(['red', 'green', 'blue']);
Set.prototype.add()
Set.prototype.add(value)
[ES6]
value
to this Set.
this
, which means that it can be chained.
const set = new Set(['red']);
set.add('green').add('blue');
assert.deepEqual(
Array.from(set), ['red', 'green', 'blue']
);
Set.prototype.delete()
Set.prototype.delete(value)
[ES6]
value
from this Set.
true
if something was deleted and false
, otherwise.
const set = new Set(['red', 'green', 'blue']);
assert.equal(set.delete('red'), true); // there was a deletion
assert.deepEqual(
Array.from(set), ['green', 'blue']
);
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);
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);
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);
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
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
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
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']]
);
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' ]
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.
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.
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.
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.
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
);
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
);
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
);
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');
});
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.
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');
});
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');
});
Promise.try()
Promise.try(callback, ...args)
[ES2025]
Creates a Promise by treating callback
as if it were a .then()
callback:
callback
with zero or more arguments.
callback
throws an exception, Promise.try()
turns it into a rejected Promise and returns it.
callback
returns a value, Promise.try()
resolves it to a Promise and returns it.
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);
});
}
Promise.all()
Promise.all(promises)
[ES6]
Promise.all<T>(
promises: Iterable<Promise<T>>
): Promise<Array<T>>
P
: if all input Promises are fulfilled.
P
: if one input Promise is rejected.
Promise.race()
Promise.race(promises)
[ES6]
Promise.race<T>(
promises: Iterable<Promise<T>>
): Promise<T>
P
: if the first input Promise is settled.
Promise.any()
Promise.any(promises)
[ES2021]
Promise.any<T>(
promises: Iterable<Promise<T>>
): Promise<T>
P
: if one input Promise is fulfilled.
P
: if all input Promises are rejected.
AggregateError
that contains the rejection values of the input Promises.
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;
}
Promise.allSettled()
Promise.allSettled(promises)
[ES2020]
Promise.allSettled<T>(
promises: Iterable<Promise<T>>
): Promise<Array<SettlementObject<T>>>
P
: if all input Promise are settled.
P
: if there is an error when iterating over the input Promises.
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;
}
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');
});
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');
});
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.
String.prototype.match()
String.prototype.match(regExpOrString)
[ES3 | /y
honors and updates .lastIndex
| /g /gy
ignore and reset .lastIndex
]
(1 of 3) regExpOrString
is a string.
If regExpOrString
is a string, it defines a pattern for a regular expression without /g
(think parameter of new RegExp()
). That regular expression is used as explained in the next list item.
(2 of 3) regExpOrString
is a RegExp without /g
.
match(
regExpOrString: string | RegExp
): null | RegExpMatchArray
interface RegExpMatchArray extends Array<string> {
index: number;
input: string;
groups: undefined | {
[key: string]: string
};
}
If regExpOrString
is a regular expression with flag /g
not set, then .match()
returns the first match for regExpOrString
within the string. Or null
if there is no match.
RegExpMatchArray
extends Array
).
.groups
.
Examples:
> 'ababb'.match(/a(b+)/)
{ 0: 'ab', 1: 'b', index: 0, input: 'ababb', groups: undefined }
> 'ababb'.match(/a(?<bs>b+)/)
{ 0: 'ab', 1: 'b', index: 0, input: 'ababb', groups: { bs: 'b' } }
> 'abab'.match(/x/)
null
(3 of 3) regExpOrString
is RegExp with /g
.
match(
regExpOrString: RegExp
): null | Array<string>
If flag /g
of regExpOrString
is set, .match()
returns either an Array with all matches or null
if there was no match.
> 'ababb'.match(/a(b+)/g)
[ 'ab', 'abb' ]
> 'ababb'.match(/a(?<bs>b+)/g)
[ 'ab', 'abb' ]
> 'abab'.match(/x/g)
null
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
};
}
/g
is not set.
RegExpMatchArray
extends Array
).
.groups
.
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 },
]
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
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”.
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.
(1 of 2) searchValue
is string or RegExp without /g
.
replace(
searchValue: string | RegExp,
replaceValue: string | (...args: any[]) => string
): string
Works similarly to .replaceAll()
, but only replaces the first occurrence:
> 'x.x.'.replace('.', '#') // interpreted literally
'x#x.'
> 'x.x.'.replace(/./, '#')
'#.x.'
(1 of 2) searchValue
is RegExp with /g
.
replace(
searchValue: RegExp,
replaceValue: string | (...args: any[]) => string
): string
Works exactly like .replaceAll()
:
> 'x.x.'.replace(/./g, '#')
'####'
> 'x.x.'.replace(/\./g, '#')
'x#x#'
String.prototype.replaceAll()
String.prototype.replaceAll(searchValue, replaceValue)
[ES2021 | /g /gy
ignore and reset .lastIndex
]
(1 of 2) replaceValue
is a string.
replaceAll(
searchValue: string | RegExp,
replaceValue: string
): string
Replaces all matches of searchValue
with replaceValue
. If searchValue
is a regular expression without flag /g
, a TypeError
is thrown.
> 'x.x.'.replaceAll('.', '#') // interpreted literally
'x#x#'
> 'x.x.'.replaceAll(/./g, '#')
'####'
> 'x.x.'.replaceAll(/./, '#')
TypeError: String.prototype.replaceAll called with
a non-global RegExp argument
Special characters in replaceValue
are:
$$
: becomes $
$n
: becomes the capture of numbered group n
(alas, $0
stands for the string '$0'
, it does not refer to the complete match)
$&
: becomes the complete match
$`
: becomes everything before the match
$'
: becomes everything after the match
$<name>
becomes the capture of named group name
(2 of 2) replaceValue
is a function.
replaceAll(
searchValue: string | RegExp,
replaceValue: (...args: any[]) => string
): string
If the second parameter is a function, occurrences are replaced with the strings it returns. Its parameters args
are:
matched: string
. The complete match
g1: string|undefined
. The capture of numbered group 1
g2: string|undefined
. The capture of numbered group 2
offset: number
. Where was the match found in the input string?
input: string
. The whole input string
const regexp = /([0-9]{2})\.([0-9]{4})/g;
const replacer = (all, month, year) => `|${year}-${month}|`;
assert.equal(
'a 12.1995 b'.replaceAll(regexp, replacer),
'a |1995-12| b'
);
Named capture groups (ES2018) are supported, too. If there are any, an argument is added at the end with an object whose properties contain the captures:
const regexp = /(?<month>[0-9]{2})\.(?<year>[0-9]{4})/g;
const replacer = (...args) => {
const groups = args.at(-1);
return `|${groups.year}-${groups.month}|`;
};
assert.equal(
'a 12.1995 b'.replaceAll(regexp, replacer),
'a |1995-12| b'
);
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.
RegExp.prototype.exec()
RegExp.prototype.exec(string)
[ES3 | /g /y /gy
honor and update .lastIndex
]
(1 of 2) Receiver is a RegExp without /g
.
Without flag /g
, regExp.exec(string)
works like string.match(regExp)
– it returns a single match object.
(2 of 2) Receiver is a RegExp with /g
.
exec(string: string): RegExpExecArray | null
interface RegExpExecArray extends Array<string> {
index: number;
input: string;
groups: undefined | {
[key: string]: string
};
}
If regExp
has flag /g
then regExp.exec(str)
returns an object for the first match starting at regExp.lastIndex
– or null
if it can’t find a match. It also updates regExp.lastIndex
so that it points to the index after the match.
RegExpExecArray
extends Array
).
.groups
.
Examples:
> const regExp = /(a+)b/g, str = 'ab aab';
> regExp.exec(str)
{0: 'ab', 1: 'a', index: 0, input: 'ab aab', groups: undefined}
> regExp.lastIndex
2
> regExp.exec(str)
{0: 'aab', 1: 'aa', index: 3, input: 'ab aab', groups: undefined}
> regExp.lastIndex
6
> regExp.exec(str)
null
> regExp.lastIndex
0