#deck:exploring-js-cards-api-preview
#html:true
#notetype:Basic
#separator:;
#columns:Front;Back;Tags
"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.NaN()
";"Number.NaN
[ES1]
The same as the global variable NaN
.
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