The project's README from github.com/zloirock/core-js. As one markdown file: README.md.

Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2026: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like
URL. You can load only required features or use it without global namespace pollution.
core-js isn't backed by a company, so the future of this project depends on you. Become a sponsor or a backer if you are interested in core-js: Open Collective, Patreon, Boosty, Bitcoin ( bc1qlea7544qtsmj2rayg0lthvza9fau63ux0fstcz ), Alipay.
import 'core-js/actual';
Promise.try(() => 42).then(it => console.log(it)); // -> 42
Array.from(new Set([1, 2, 3]).union(new Set([3, 4, 5]))); // => [1, 2, 3, 4, 5]
[1, 2].flatMap(it => [it, it]); // => [1, 1, 2, 2]
Iterator.concat([1, 2], function * (i) { while (true) yield i++; }(3))
.drop(1).take(5)
.filter(it => it % 2)
.map(it => it ** 2)
.toArray(); // => [9, 25]
structuredClone(new Set([1, 2, 3])); // => Set { 1, 2, 3 }
You can load only required features:
import 'core-js/actual/promise';
import 'core-js/actual/set';
import 'core-js/actual/iterator';
import 'core-js/actual/array/from';
import 'core-js/actual/array/flat-map';
import 'core-js/actual/structured-clone';
Promise.try(() => 42).then(it => console.log(it)); // -> 42
Array.from(new Set([1, 2, 3]).union(new Set([3, 4, 5]))); // => [1, 2, 3, 4, 5]
[1, 2].flatMap(it => [it, it]); // => [1, 1, 2, 2]
Iterator.concat([1, 2], function * (i) { while (true) yield i++; }(3))
.drop(1).take(5)
.filter(it => it % 2)
.map(it => it ** 2)
.toArray(); // => [9, 25]
structuredClone(new Set([1, 2, 3])); // => Set { 1, 2, 3 }
Or use it without global namespace pollution:
import Promise from 'core-js-pure/actual/promise';
import Set from 'core-js-pure/actual/set';
import Iterator from 'core-js-pure/actual/iterator';
import from from 'core-js-pure/actual/array/from';
import flatMap from 'core-js-pure/actual/array/flat-map';
import structuredClone from 'core-js-pure/actual/structured-clone';
Promise.try(() => 42).then(it => console.log(it)); // -> 42
from(new Set([1, 2, 3]).union(new Set([3, 4, 5]))); // => [1, 2, 3, 4, 5]
flatMap([1, 2], it => [it, it]); // => [1, 1, 2, 2]
Iterator.concat([1, 2], function * (i) { while (true) yield i++; }(3))
.drop(1).take(5)
.filter(it => it % 2)
.map(it => it ** 2)
.toArray(); // => [9, 25]
structuredClone(new Set([1, 2, 3])); // => Set { 1, 2, 3 }
globalThisArray.prototype.includesArray.prototype.flat / Array.prototype.flatMapArray by copyArray groupingArray.fromAsyncArrayBuffer.prototype.transfer and friendsUint8Array to / from base64 and hexError causeError.isErrorFloat16 methodsIterator helpersIterator sequencingIterator chunkingIterator includesIterator joinObject.values / Object.entriesObject.fromEntriesObject.getOwnPropertyDescriptorsObject.prototype.hasOwnPropertyString paddingString.prototype.matchAllString.prototype.replaceAllString.prototype.trimStart / String.prototype.trimEndRegExp s (dotAll) flagRegExp named capture groupsRegExp escapingPromise.allSettledPromise.anyPromise.prototype.finallyPromise.tryPromise.withResolversSymbol.asyncIterator for asynchronous iterationSymbol.prototype.descriptionJSON.parse source text accessJSON.stringifySet methodsMap upsertMath.sumPrecise# global version
npm install --save [email protected]
# version without global namespace pollution
npm install --save [email protected]
# bundled global version
npm install --save [email protected]
postinstall message⬆The core-js project needs your help, so the package shows a message about it after installation. If it causes problems for you, you can disable it:
ADBLOCK=true npm install
# or
DISABLE_OPENCOLLECTIVE=true npm install
# or
npm install --loglevel silent
You can import only the polyfills you need, like in the examples at the top of README.md, using public CommonJS entry points for namespaces, proposals, constructors and individual methods (listed under Features). Some methods do not have separate entry points and are loaded through their constructor or family entry point instead - for example, DataView.prototype.setInt8 is provided by core-js/actual/data-view (see ECMAScript: Typed arrays). Just some examples:
// polyfill all `core-js` features, including early-stage proposals:
import 'core-js';
// or:
import 'core-js/full';
// polyfill all actual features - stable ES, web standards and stage 3 ES proposals:
import 'core-js/actual';
// polyfill only stable features - ES and web standards:
import 'core-js/stable';
// polyfill only stable ES features:
import 'core-js/es';
// if you want to polyfill `Set`:
// all `Set`-related features, with early-stage ES proposals:
import 'core-js/full/set';
// stable required for `Set` ES features, features from web standards and stage 3 ES proposals:
import 'core-js/actual/set';
// stable required for `Set` ES features and features from web standards
// (DOM collections iterator in this case):
import 'core-js/stable/set';
// only stable ES features required for `Set`:
import 'core-js/es/set';
// the same without global namespace pollution:
import Set from "core-js-pure/full/set";
import Set from "core-js-pure/actual/set";
import Set from "core-js-pure/stable/set";
import Set from "core-js-pure/es/set";
// if you want to polyfill just the required methods:
import 'core-js/full/set/intersection';
import 'core-js/actual/array/find-last';
import 'core-js/stable/queue-microtask';
import 'core-js/es/array/from';
// polyfill async iterator helpers proposal:
import 'core-js/proposals/async-iterator-helpers';
// polyfill all stage 2+ proposals:
import 'core-js/stage/2';
[!TIP] The usage of the
/actual/namespace is recommended since it includes all actual JavaScript features and does not include unstable early-stage proposals that are available mainly for experiments.
[!WARNING]
- The
modulespath is an internal API, does not inject all required dependencies and can be changed in minor or patch releases. Use it only for a custom build and/or if you know what you are doing.- If you use
core-jswith the extension of native objects, recommended to load allcore-jsmodules at the top of the entry point of your application, otherwise, you can have conflicts.
- For example, Google Maps uses its own
Symbol.iterator, conflicting withArray.from,URLSearchParamsand / or something else fromcore-js, see related issues.- Such conflicts are also resolvable by discovering and manually adding each conflicting entry from
core-js.core-jsis extremely modular and uses a lot of very tiny modules, because of that, for usage in browsers, bundle upcore-jsinstead of using a loader for each file; otherwise, you will have hundreds of requests.
In the pure version, we can't pollute prototypes of native constructors. Because of that, prototype methods are transformed into static methods, like in the examples above. But with transpilers, we can use one more trick - bind operator and virtual methods. For this case, there are /virtual/ entry points. Example:
import fill from 'core-js-pure/actual/array/virtual/fill';
import findIndex from 'core-js-pure/actual/array/virtual/find-index';
Array(10)::fill(0).map((a, b) => b * b)::findIndex(it => it && !(it % 8)); // => 4
[!WARNING] The bind operator is an early-stage ECMAScript proposal and usage of this syntax can be dangerous.
core-js is integrated with babel and is the base for polyfilling-related babel features:
[!NOTE]
useBuiltInsandcorejsoptions described below are available only in Babel 7; in Babel 8, they were replaced withbabel-plugin-polyfill-corejs3.
@babel/polyfill⬆@babel/polyfill IS just the import of stable core-js features and regenerator-runtime for generators and async functions, so loading @babel/polyfill means loading the global version of core-js without ES proposals.
Now it's deprecated in favor of separate inclusion of required parts of core-js and regenerator-runtime and, for backward compatibility, @babel/polyfill is still based on core-js@2.
As a full equivalent of @babel/polyfill, you can use the following:
import 'core-js/stable';
import 'regenerator-runtime/runtime';
@babel/preset-env⬆@babel/preset-env has useBuiltIns option, which optimizes the use of the global version of core-js. With useBuiltIns option, you should also set corejs option to the used version of core-js, like corejs: '3.51'.
[!IMPORTANT] It is recommended to specify the used minor
core-jsversion, likecorejs: '3.51', instead ofcorejs: 3, since withcorejs: 3, modules added in minorcore-jsreleases will not be injected.
useBuiltIns: 'entry' replaces imports of core-js with imports of only the modules required for a target environment. So, for example,import 'core-js/stable';
with chrome 71 target will be replaced just to:
import 'core-js/modules/es.array.unscopables.flat';
import 'core-js/modules/es.array.unscopables.flat-map';
import 'core-js/modules/es.object.from-entries';
import 'core-js/modules/web.immediate';
// ...and the rest of the modules not yet supported by Chrome 71
It works for all entry points of global version of core-js and their combinations, for example for
import 'core-js/es';
import 'core-js/proposals/set-methods';
import 'core-js/full/set/map';
with chrome 71 target you will have as the result:
import 'core-js/modules/es.array.unscopables.flat';
import 'core-js/modules/es.array.unscopables.flat-map';
import 'core-js/modules/es.object.from-entries';
import 'core-js/modules/esnext.set.difference';
import 'core-js/modules/esnext.set.intersection';
import 'core-js/modules/esnext.set.is-disjoint-from';
import 'core-js/modules/esnext.set.is-subset-of';
import 'core-js/modules/esnext.set.is-superset-of';
import 'core-js/modules/esnext.set.map';
import 'core-js/modules/esnext.set.symmetric-difference';
import 'core-js/modules/esnext.set.union';
// ...and the rest of the modules not yet supported by Chrome 71
useBuiltIns: 'usage' adds to the top of each file imports of polyfills for features used in this file and not supported by target environments, so for:// first file:
let set = new Set([1, 2, 3]);
// second file:
let array = Array.of(1, 2, 3);
if the target contains an old environment like IE 11 we will have something like:
// first file:
import 'core-js/modules/es.array.iterator';
import 'core-js/modules/es.object.to-string';
import 'core-js/modules/es.set';
var set = new Set([1, 2, 3]);
// second file:
import 'core-js/modules/es.array.of';
var array = Array.of(1, 2, 3);
By default, @babel/preset-env with useBuiltIns: 'usage' option only polyfills stable features, but you can enable polyfilling of proposals by the proposals option, as corejs: { version: '3.51', proposals: true }.
[!IMPORTANT] In the case of
useBuiltIns: 'usage', you should not addcore-jsimports by yourself, they will be added automatically.
@babel/runtime⬆@babel/plugin-transform-runtime with corejs: 3 option simplifies work with the core-js-pure. It automatically replaces the usage of modern features from the JS standard library to imports from the version of core-js without global namespace pollution, so instead of:
import from from 'core-js-pure/stable/array/from';
import flat from 'core-js-pure/stable/array/flat';
import Set from 'core-js-pure/stable/set';
import Promise from 'core-js-pure/stable/promise';
from(new Set([1, 2, 3, 2, 1]));
flat([1, [2, 3], [4, [5]]], 2);
Promise.resolve(32).then(x => console.log(x));
you can write just:
Array.from(new Set([1, 2, 3, 2, 1]));
[1, [2, 3], [4, [5]]].flat(2);
Promise.resolve(32).then(x => console.log(x));
By default, @babel/plugin-transform-runtime only polyfills stable features, but like in @babel/preset-env, you can enable polyfilling of proposals by proposals option, as corejs: { version: 3, proposals: true }.
[!WARNING] If you use
@babel/preset-envand@babel/plugin-transform-runtimetogether, usecorejsoption only in one place since it's duplicate functionality and will cause conflicts.
babel-plugin-polyfill-corejs3⬆babel-plugin-polyfill-corejs3 is a babel plugin for injection of core-js polyfills. In Babel 8, useBuiltIns and corejs options were removed from @babel/preset-env and @babel/plugin-transform-runtime in favor of this plugin; it also works with Babel 7. It has 3 methods: entry-global (like useBuiltIns: 'entry'), usage-global (like useBuiltIns: 'usage') and usage-pure (like @babel/plugin-transform-runtime with corejs: 3 option). Like with corejs option, it's recommended to specify the used minor core-js version by version option, and polyfilling of proposals can be enabled by proposals: true option. Example of configuration in babel.config.json:
{
"plugins": [["polyfill-corejs3", { "method": "usage-global", "version": "3.51" }]]
}
Fast JavaScript transpiler swc contains integration with core-js, that optimizes work with the global version of core-js. Like @babel/preset-env, it has 2 modes: usage and entry, but usage mode still works not so well as in babel. Example of configuration in .swcrc:
{
"env": {
"targets": "> 0.25%, not dead",
"mode": "entry",
"coreJs": "3.51"
}
}
By default, core-js sets polyfills only when they are required. That means that core-js checks if a feature is available and works correctly or not and if it has no problems, core-js uses native implementation.
But sometimes core-js feature detection could be too strict for your case. For example, Promise constructor requires support for unhandled rejection tracking and @@species.
Sometimes we could have an inverse problem - a knowingly broken environment with problems not covered by core-js feature detection.
For those cases, we could redefine this behavior for certain polyfills:
const configurator = require('core-js/configurator');
configurator({
useNative: ['Promise'], // polyfills will be used only if natives are completely unavailable
usePolyfill: ['Array.from', 'String.prototype.padEnd'], // polyfills will be used anyway
useFeatureDetection: ['Map', 'Set'], // default behavior
});
require('core-js/actual');
It does not work with some features. Also, if you change the default behavior, even core-js internals may not work correctly.
In some cases, it could be useful to exclude some core-js features or to generate a polyfill for target engines. You can use the core-js-builder package for that.
core-js tries to support all possible JS engines and environments with ES3 support. Some features have a higher lower bar - for example, some accessors can properly work only from ES5, promises require a way to set a microtask or a task, etc.
However, I have no possibility to test core-js absolutely everywhere - for example, testing in IE7- and some other ancient engines was stopped. You can see the list of definitely supported engines in the compatibility table at the link below. Write if you have issues or questions with the support of any engine.
The core-js project provides (as the core-js-compat package) all required data about the necessity of core-js modules, entry points, and tools to work with it - it's useful for integration with tools like babel or swc. If you want to help, you could take a look at the related section of CONTRIBUTING.md. The visualization of compatibility data and the browser tests runner is available here, the example:

core-js(-pure)
core-js(-pure)/es
Modules es.object.assign, es.object.create, es.object.define-getter, es.object.define-property, es.object.define-properties, es.object.define-setter, es.object.entries, es.object.freeze, es.object.from-entries, es.object.get-own-property-descriptor, es.object.get-own-property-descriptors, es.object.get-own-property-names, es.object.get-prototype-of, es.object.group-by, es.object.has-own, es.object.is, es.object.is-extensible, es.object.is-frozen, es.object.is-sealed, es.object.keys, es.object.lookup-setter, es.object.lookup-getter, es.object.prevent-extensions, es.object.proto, es.object.to-string, es.object.seal, es.object.set-prototype-of, es.object.values.
class Object {
toString(): string; // ES2015+ fix: @@toStringTag support
__defineGetter__(property: PropertyKey, getter: Function): void;
__defineSetter__(property: PropertyKey, setter: Function): void;
__lookupGetter__(property: PropertyKey): Function | void;
__lookupSetter__(property: PropertyKey): Function | void;
__proto__: Object | null; // requires a way to set the prototype - does not work in IE10-, it's for modern engines like Deno
static assign(target: Object, ...sources: Array<Object>): Object;
static create(prototype: Object | null, properties?: { [property: PropertyKey]: PropertyDescriptor }): Object;
static defineProperties(object: Object, properties: { [property: PropertyKey]: PropertyDescriptor }): Object;
static defineProperty(object: Object, property: PropertyKey, attributes: PropertyDescriptor): Object;
static entries(object: Object): Array<[string, mixed]>;
static freeze(object: any): any;
static fromEntries(iterable: Iterable<[key, value]>): Object;
static getOwnPropertyDescriptor(object: any, property: PropertyKey): PropertyDescriptor | void;
static getOwnPropertyDescriptors(object: any): { [property: PropertyKey]: PropertyDescriptor };
static getOwnPropertyNames(object: any): Array<string>;
static getPrototypeOf(object: any): Object | null;
static groupBy(items: Iterable, callbackfn: (value: any, index: number) => key): { [key]: Array<mixed> };
static hasOwn(value: any, key: PropertyKey): boolean; // throws if value is null or undefined
static is(value1: any, value2: any): boolean;
static isExtensible(object: any): boolean;
static isFrozen(object: any): boolean;
static isSealed(object: any): boolean;
static keys(object: any): Array<string>;
static preventExtensions(object: any): any;
static seal(object: any): any;
static setPrototypeOf(target: any, prototype: Object | null): any; // requires __proto__ - IE11+
static values(object: any): Array<mixed>;
}
core-js(-pure)/es|stable|actual|full/object
core-js(-pure)/es|stable|actual|full/object/assign
core-js(-pure)/es|stable|actual|full/object/is
core-js(-pure)/es|stable|actual|full/object/set-prototype-of
core-js(-pure)/es|stable|actual|full/object/get-prototype-of
core-js(-pure)/es|stable|actual|full/object/create
core-js(-pure)/es|stable|actual|full/object/define-property
core-js(-pure)/es|stable|actual|full/object/define-properties
core-js(-pure)/es|stable|actual|full/object/get-own-property-descriptor
core-js(-pure)/es|stable|actual|full/object/get-own-property-descriptors
core-js(-pure)/es|stable|actual|full/object/group-by
core-js(-pure)/es|stable|actual|full/object/has-own
core-js(-pure)/es|stable|actual|full/object/keys
core-js(-pure)/es|stable|actual|full/object/values
core-js(-pure)/es|stable|actual|full/object/entries
core-js(-pure)/es|stable|actual|full/object/get-own-property-names
core-js(-pure)/es|stable|actual|full/object/freeze
core-js(-pure)/es|stable|actual|full/object/from-entries
core-js(-pure)/es|stable|actual|full/object/seal
core-js(-pure)/es|stable|actual|full/object/prevent-extensions
core-js/es|stable|actual|full/object/proto
core-js(-pure)/es|stable|actual|full/object/is-frozen
core-js(-pure)/es|stable|actual|full/object/is-sealed
core-js(-pure)/es|stable|actual|full/object/is-extensible
core-js/es|stable|actual|full/object/to-string
core-js(-pure)/es|stable|actual|full/object/define-getter
core-js(-pure)/es|stable|actual|full/object/define-setter
core-js(-pure)/es|stable|actual|full/object/lookup-getter
core-js(-pure)/es|stable|actual|full/object/lookup-setter
Examples:
let foo = { q: 1, w: 2 };
let bar = { e: 3, r: 4 };
let baz = { t: 5, y: 6 };
Object.assign(foo, bar, baz); // => foo = { q: 1, w: 2, e: 3, r: 4, t: 5, y: 6 }
Object.is(NaN, NaN); // => true
Object.is(0, -0); // => false
Object.is(42, 42); // => true
Object.is(42, '42'); // => false
function Parent() { /* empty */ }
function Child() { /* empty */ }
Object.setPrototypeOf(Child.prototype, Parent.prototype);
new Child() instanceof Child; // => true
new Child() instanceof Parent; // => true
({
[Symbol.toStringTag]: 'Foo',
}).toString(); // => '[object Foo]'
Object.keys('qwe'); // => ['0', '1', '2']
Object.getPrototypeOf('qwe') === String.prototype; // => true
Object.values({ a: 1, b: 2, c: 3 }); // => [1, 2, 3]
Object.entries({ a: 1, b: 2, c: 3 }); // => [['a', 1], ['b', 2], ['c', 3]]
for (let [key, value] of Object.entries({ a: 1, b: 2, c: 3 })) {
console.log(key); // -> 'a', 'b', 'c'
console.log(value); // -> 1, 2, 3
}
// Shallow object cloning with prototype and descriptors:
let copy = Object.create(Object.getPrototypeOf(object), Object.getOwnPropertyDescriptors(object));
// Mixin:
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
const map = new Map([['a', 1], ['b', 2]]);
Object.fromEntries(map); // => { a: 1, b: 2 }
class Unit {
constructor(id) {
this.id = id;
}
toString() {
return `unit${ this.id }`;
}
}
const units = new Set([new Unit(101), new Unit(102)]);
Object.fromEntries(units.entries()); // => { unit101: Unit { id: 101 }, unit102: Unit { id: 102 } }
Object.hasOwn({ foo: 42 }, 'foo'); // => true
Object.hasOwn({ foo: 42 }, 'bar'); // => false
Object.hasOwn({}, 'toString'); // => false
Object.groupBy([1, 2, 3, 4, 5], it => it % 2); // => { 1: [1, 3, 5], 0: [2, 4] }
Modules es.function.name, es.function.has-instance. Just ES5: es.function.bind.
class Function {
name: string;
bind(thisArg: any, ...args: Array<mixed>): Function;
@@hasInstance(value: any): boolean;
}
core-js/es|stable|actual|full/function
core-js(-pure)/es|stable|actual|full/function/virtual
core-js/es|stable|actual|full/function/name
core-js/es|stable|actual|full/function/has-instance
core-js(-pure)/es|stable|actual|full/function/bind
core-js(-pure)/es|stable|actual|full/function/virtual/bind
(function foo() { /* empty */ }).name; // => 'foo'
console.log.bind(console, 42)(43); // -> 42 43
Modules es.aggregate-error, es.aggregate-error.cause, es.error.cause, es.error.is-error, es.suppressed-error.constructor, es.error.to-string.
class Error {
static isError(value: any): boolean;
constructor(message?: string, { cause: any }?): %Error%;
toString(): string; // different fixes
}
class [
EvalError,
RangeError,
ReferenceError,
SyntaxError,
TypeError,
URIError,
WebAssembly.CompileError,
WebAssembly.LinkError,
WebAssembly.RuntimeError,
] extends Error {
constructor(message?: string, { cause: any }?): %Error%;
}
class AggregateError extends Error {
constructor(errors: Iterable, message?: string, { cause: any }?): AggregateError;
errors: Array<any>;
message: string;
cause: any;
}
class SuppressedError extends Error {
constructor(error: any, suppressed: any, message?: string): SuppressedError;
error: any;
suppressed: any;
message: string;
}
core-js/es|stable|actual|full/error
core-js/es|stable|actual|full/error/constructor
core-js(-pure)/es|stable|actual|full/error/is-error
core-js/es|stable|actual|full/error/to-string
core-js(-pure)/es|stable|actual|full/aggregate-error
core-js(-pure)/es|stable|actual|full/suppressed-error
const error1 = new TypeError('Error 1');
const error2 = new TypeError('Error 2');
const aggregate = new AggregateError([error1, error2], 'Collected errors');
aggregate.errors[0] === error1; // => true
aggregate.errors[1] === error2; // => true
const cause = new TypeError('Something wrong');
const error = new TypeError('Here is what went wrong', { cause });
error.cause === cause; // => true
Error.prototype.toString.call({ message: 1, name: 2 }) === '2: 1'; // => true
Error.isError(new Error('error')); // => true
Error.isError(new TypeError('error')); // => true
Error.isError(new DOMException('error')); // => true
Error.isError(null); // => false
Error.isError({}); // => false
Error.isError(Object.create(Error.prototype)); // => false
[!WARNING] We have no bulletproof way to polyfill this
Error.isError/ check if the object is an error, so it's a rather naive implementation.
Modules es.array.from, es.array.from-async, es.array.is-array, es.array.of, es.array.species, es.array.concat, es.array.copy-within, es.array.fill, es.array.find, es.array.find-index, es.array.find-last, es.array.find-last-index, es.array.iterator, es.array.includes, es.array.push, es.array.slice, es.array.splice, es.array.join, es.array.unshift, es.array.index-of, es.array.last-index-of, es.array.every, es.array.some, es.array.for-each, es.array.map, es.array.filter, es.array.reduce, es.array.reduce-right, es.array.reverse, es.array.sort, es.array.flat, es.array.flat-map, es.array.unscopables.flat, es.array.unscopables.flat-map, es.array.at, es.array.to-reversed, es.array.to-sorted, es.array.to-spliced, es.array.with.
class Array {
at(index: int): any;
concat(...args: Array<mixed>): Array<mixed>; // with added support for @@isConcatSpreadable and @@species
copyWithin(target: number, start: number, end?: number): this;
entries(): Iterator<[index, value]>;
every(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): boolean;
fill(value: any, start?: number, end?: number): this;
filter(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): Array<mixed>; // with added support for @@species
find(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): any;
findIndex(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): number;
findLast(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): any;
findLastIndex(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): number;
flat(depthArg?: number = 1): Array<mixed>;
flatMap(mapFn: (value: any, index: number, target: any) => any, thisArg?: any): Array<mixed>;
forEach(callbackfn: (value: any, index: number, target: any) => void, thisArg?: any): void;
includes(searchElement: any, from?: number): boolean;
indexOf(searchElement: any, from?: number): number;
join(separator: string = ','): string;
keys(): Iterator<index>;
lastIndexOf(searchElement: any, from?: number): number;
map(mapFn: (value: any, index: number, target: any) => any, thisArg?: any): Array<mixed>; // with added support for @@species
push(...args: Array<mixed>): uint;
reduce(callbackfn: (memo: any, value: any, index: number, target: any) => any, initialValue?: any): any;
reduceRight(callbackfn: (memo: any, value: any, index: number, target: any) => any, initialValue?: any): any;
reverse(): this; // Safari 12.0 bug fix
slice(start?: number, end?: number): Array<mixed>; // with added support for @@species
splice(start?: number, deleteCount?: number, ...items: Array<mixed>): Array<mixed>; // with added support for @@species
some(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): boolean;
sort(comparefn?: (a: any, b: any) => number): this; // with modern behavior like stable sort
toReversed(): Array<mixed>;
toSpliced(start?: number, deleteCount?: number, ...items: Array<mixed>): Array<mixed>;
toSorted(comparefn?: (a: any, b: any) => number): Array<mixed>;
unshift(...args: Array<mixed>): uint;
values(): Iterator<value>;
with(index: int, value: any): Array<mixed>;
@@iterator(): Iterator<value>;
@@unscopables: { [newMethodNames: string]: true };
static from(items: Iterable | ArrayLike, mapFn?: (value: any, index: number) => any, thisArg?: any): Array<mixed>;
static fromAsync(asyncItems: AsyncIterable | Iterable | ArrayLike, mapFn?: (value: any, index: number) => any, thisArg?: any): Promise<Array<mixed>>;
static isArray(value: any): boolean;
static of(...args: Array<mixed>): Array<mixed>;
static readonly attribute @@species: this;
}
class Arguments {
@@iterator(): Iterator<value>; // available only in core-js methods
}
core-js(-pure)/es|stable|actual|full/array
core-js(-pure)/es|stable|actual|full/array/virtual
core-js(-pure)/es|stable|actual|full/array/from
core-js(-pure)/es|stable|actual|full/array/from-async
core-js(-pure)/es|stable|actual|full/array/of
core-js(-pure)/es|stable|actual|full/array/is-array
core-js(-pure)/es|stable|actual|full/array(/virtual)/at
core-js(-pure)/es|stable|actual|full/array(/virtual)/concat
core-js(-pure)/es|stable|actual|full/array(/virtual)/copy-within
core-js(-pure)/es|stable|actual|full/array(/virtual)/entries
core-js(-pure)/es|stable|actual|full/array(/virtual)/every
core-js(-pure)/es|stable|actual|full/array(/virtual)/fill
core-js(-pure)/es|stable|actual|full/array(/virtual)/filter
core-js(-pure)/es|stable|actual|full/array(/virtual)/find
core-js(-pure)/es|stable|actual|full/array(/virtual)/find-index
core-js(-pure)/es|stable|actual|full/array(/virtual)/find-last
core-js(-pure)/es|stable|actual|full/array(/virtual)/find-last-index
core-js(-pure)/es|stable|actual|full/array(/virtual)/flat
core-js(-pure)/es|stable|actual|full/array(/virtual)/flat-map
core-js(-pure)/es|stable|actual|full/array(/virtual)/for-each
core-js(-pure)/es|stable|actual|full/array(/virtual)/includes
core-js(-pure)/es|stable|actual|full/array(/virtual)/index-of
core-js(-pure)/es|stable|actual|full/array(/virtual)/iterator
core-js(-pure)/es|stable|actual|full/array(/virtual)/join
core-js(-pure)/es|stable|actual|full/array(/virtual)/keys
core-js(-pure)/es|stable|actual|full/array(/virtual)/last-index-of
core-js(-pure)/es|stable|actual|full/array(/virtual)/map
core-js(-pure)/es|stable|actual|full/array(/virtual)/push
core-js(-pure)/es|stable|actual|full/array(/virtual)/reduce
core-js(-pure)/es|stable|actual|full/array(/virtual)/reduce-right
core-js(-pure)/es|stable|actual|full/array(/virtual)/reverse
core-js(-pure)/es|stable|actual|full/array(/virtual)/slice
core-js(-pure)/es|stable|actual|full/array(/virtual)/some
core-js(-pure)/es|stable|actual|full/array(/virtual)/sort
core-js(-pure)/es|stable|actual|full/array(/virtual)/splice
core-js(-pure)/es|stable|actual|full/array(/virtual)/to-reversed
core-js(-pure)/es|stable|actual|full/array(/virtual)/to-sorted
core-js(-pure)/es|stable|actual|full/array(/virtual)/to-spliced
core-js(-pure)/es|stable|actual|full/array(/virtual)/unshift
core-js(-pure)/es|stable|actual|full/array(/virtual)/values
core-js(-pure)/es|stable|actual|full/array(/virtual)/with
Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
Array.from({ 0: 1, 1: 2, 2: 3, length: 3 }); // => [1, 2, 3]
Array.from('123', Number); // => [1, 2, 3]
Array.from('123', it => it ** 2); // => [1, 4, 9]
Array.of(1); // => [1]
Array.of(1, 2, 3); // => [1, 2, 3]
let array = ['a', 'b', 'c'];
for (let value of array) console.log(value); // -> 'a', 'b', 'c'
for (let value of array.values()) console.log(value); // -> 'a', 'b', 'c'
for (let key of array.keys()) console.log(key); // -> 0, 1, 2
for (let [key, value] of array.entries()) {
console.log(key); // -> 0, 1, 2
console.log(value); // -> 'a', 'b', 'c'
}
function isOdd(value) {
return value % 2;
}
[4, 8, 15, 16, 23, 42].find(isOdd); // => 15
[4, 8, 15, 16, 23, 42].findIndex(isOdd); // => 2
[1, 2, 3, 4].findLast(isOdd); // => 3
[1, 2, 3, 4].findLastIndex(isOdd); // => 2
Array(5).fill(42); // => [42, 42, 42, 42, 42]
[1, 2, 3, 4, 5].copyWithin(0, 3); // => [4, 5, 3, 4, 5]
[1, 2, 3].includes(2); // => true
[1, 2, 3].includes(4); // => false
[1, 2, 3].includes(2, 2); // => false
[NaN].indexOf(NaN); // => -1
[NaN].includes(NaN); // => true
Array(1).indexOf(undefined); // => -1
Array(1).includes(undefined); // => true
[1, [2, 3], [4, 5]].flat(); // => [1, 2, 3, 4, 5]
[1, [2, [3, [4]]], 5].flat(); // => [1, 2, [3, [4]], 5]
[1, [2, [3, [4]]], 5].flat(3); // => [1, 2, 3, 4, 5]
[{ a: 1, b: 2 }, { a: 3, b: 4 }, { a: 5, b: 6 }].flatMap(it => [it.a, it.b]); // => [1, 2, 3, 4, 5, 6]
[1, 2, 3].at(1); // => 2
[1, 2, 3].at(-1); // => 3
const sequence = [1, 2, 3];
sequence.toReversed(); // => [3, 2, 1]
sequence; // => [1, 2, 3]
const initialArray = [1, 2, 3, 4];
initialArray.toSpliced(1, 2, 5, 6, 7); // => [1, 5, 6, 7, 4]
initialArray; // => [1, 2, 3, 4]
const outOfOrder = [3, 1, 2];
outOfOrder.toSorted(); // => [1, 2, 3]
outOfOrder; // => [3, 1, 2]
const correctionNeeded = [1, 1, 3];
correctionNeeded.with(1, 2); // => [1, 2, 3]
correctionNeeded; // => [1, 1, 3]
await Array.fromAsync((async function * () { yield * [1, 2, 3]; })(), i => i ** 2); // => [1, 4, 9]
Modules es.iterator.constructor, es.iterator.chunks, es.iterator.concat, es.iterator.dispose, es.iterator.drop, es.iterator.every, es.iterator.filter, es.iterator.find, es.iterator.flat-map, es.iterator.for-each, es.iterator.from, es.iterator.includes, es.iterator.join, es.iterator.map, es.iterator.reduce, es.iterator.some, es.iterator.take, es.iterator.to-array, es.iterator.windows, es.iterator.zip, es.iterator.zip-keyed.
type ZipSource<T> = IterableObject<T> | Iterator<T>;
class Iterator {
static concat(...items: Array<IterableObject>): Iterator<any>;
static from(iterable: Iterable<any> | Iterator<any>): Iterator<any>;
static zip(iterables: Iterable<ZipSource<value>>, options?: { mode?: 'shortest' | 'strict' = 'shortest' }): Iterator<Array<value>>;
static zip(iterables: Iterable<ZipSource<value>>, options: {
mode: 'longest', padding?: IterableObject<paddingValue>,
}): Iterator<Array<value | paddingValue | undefined>>;
static zipKeyed(iterables: Record<key, ZipSource<value> | undefined>, options?: {
mode?: 'shortest' | 'strict' = 'shortest',
}): Iterator<Partial<Record<key, value>>>;
static zipKeyed(iterables: Record<key, ZipSource<value> | undefined>, options: {
mode: 'longest', padding?: Partial<Record<key, paddingValue>>,
}): Iterator<Partial<Record<key, value | paddingValue | undefined>>>;
chunks(chunkSize: number): Iterator<any>;
drop(limit: uint): Iterator<any>;
every(callbackfn: (value: any, counter: uint) => boolean): boolean;
filter(callbackfn: (value: any, counter: uint) => boolean): Iterator<any>;
find(callbackfn: (value: any, counter: uint) => boolean): any;
flatMap(callbackfn: (value: any, counter: uint) => IterableObject<any> | Iterator<any>): Iterator<any>;
forEach(callbackfn: (value: any, counter: uint) => void): void;
includes(searchElement: any, skippedElements?: number): boolean;
join(separator?: string): string;
map(callbackfn: (value: any, counter: uint) => any): Iterator<any>;
reduce(callbackfn: (memo: any, value: any, counter: uint) => any, initialValue?: any): any;
some(callbackfn: (value: any, counter: uint) => boolean): boolean;
take(limit: uint): Iterator<any>;
toArray(): Array<any>;
windows(windowSize: number, undersized?: 'only-full' | 'allow-partial' | undefined): Iterator<any>;
@@dispose(): undefined;
@@toStringTag: 'Iterator';
}
core-js(-pure)/es|stable|actual|full/iterator
core-js(-pure)/es|stable|actual|full/iterator/chunks
core-js(-pure)/es|stable|actual|full/iterator/concat
core-js(-pure)/es|stable|actual|full/iterator/dispose
core-js(-pure)/es|stable|actual|full/iterator/drop
core-js(-pure)/es|stable|actual|full/iterator/every
core-js(-pure)/es|stable|actual|full/iterator/filter
core-js(-pure)/es|stable|actual|full/iterator/find
core-js(-pure)/es|stable|actual|full/iterator/flat-map
core-js(-pure)/es|stable|actual|full/iterator/for-each
core-js(-pure)/es|stable|actual|full/iterator/from
core-js(-pure)/es|stable|actual|full/iterator/includes
core-js(-pure)/es|stable|actual|full/iterator/join
core-js(-pure)/es|stable|actual|full/iterator/map
core-js(-pure)/es|stable|actual|full/iterator/reduce
core-js(-pure)/es|stable|actual|full/iterator/some
core-js(-pure)/es|stable|actual|full/iterator/take
core-js(-pure)/es|stable|actual|full/iterator/to-array
core-js(-pure)/es|stable|actual|full/iterator/windows
core-js(-pure)/es|stable|actual|full/iterator/zip
core-js(-pure)/es|stable|actual|full/iterator/zip-keyed
[1, 2, 3, 4, 5, 6, 7].values()
.drop(1)
.take(5)
.filter(it => it % 2)
.map(it => it ** 2)
.toArray(); // => [9, 25]
Iterator.from({
next: () => ({ done: Math.random() > 0.9, value: Math.random() * 10 | 0 }),
}).toArray(); // => [7, 6, 3, 0, 2, 8]
Iterator.concat([0, 1].values(), [2, 3], function * () {
yield 4;
yield 5;
}()).toArray(); // => [0, 1, 2, 3, 4, 5]
Iterator.zip([
[0, 1, 2],
[3, 4, 5],
]).toArray(); // => [[0, 3], [1, 4], [2, 5]]
Iterator.zipKeyed({
a: [0, 1, 2],
b: [3, 4, 5, 6],
c: [7, 8, 9],
}, {
mode: 'longest',
padding: { c: 10 },
}).toArray(); // =>
/*
[
{ a: 0, b: 3, c: 7 },
{ a: 1, b: 4, c: 8 },
{ a: 2, b: 5, c: 9 },
{ a: undefined, b: 6, c: 10 },
];
*/
const digits = () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].values();
Array.from(digits().chunks(2)); // => [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
Array.from(digits().windows(2)); // => [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
Array.from([0, 1].values().windows(3, 'allow-partial')); // => [[0, 1]]
Array.from([0, 1].values().windows(3)); // => []
[1, 2, 3].values().includes(2); // => true
[1, 2, 3].values().includes(4); // => false
[NaN].values().includes(NaN); // => true
[1, 2, 3].values().includes(3, 2); // => true
[1, 2, 3].values().includes(1, 1); // => false
[1, 2, 3].values().join(); // => '1,2,3'
[1, 2, 3].values().join('-'); // => '1-2-3'
[1, null, 3].values().join(); // => '1,,3'
[!WARNING]
- To prevent prototype pollution, in the
pureversion, new%IteratorPrototype%methods are not added to the real%IteratorPrototype%, they are available only on wrappers - instead of[].values().map(fn)useIterator.from([]).map(fn).
The main part of String features: modules es.string.from-code-point, es.string.raw, es.string.iterator, es.string.split, es.string.code-point-at, es.string.ends-with, es.string.includes, es.string.repeat, es.string.pad-start, es.string.pad-end, es.string.starts-with, es.string.trim, es.string.trim-start, es.string.trim-end, es.string.match-all, es.string.replace-all, es.string.at-alternative, es.string.is-well-formed, es.string.to-well-formed.
Added support for well-known symbols @@match, @@replace, @@search and @@split and direct .exec calls to the related String methods, modules es.string.match, es.string.replace, es.string.search and es.string.split.
Annex B methods. Modules es.string.anchor, es.string.big, es.string.blink, es.string.bold, es.string.fixed, es.string.fontcolor, es.string.fontsize, es.string.italics, es.string.link, es.string.small, es.string.strike, es.string.sub, es.string.sup, es.string.substr, es.escape and es.unescape.
RegExp features: modules es.regexp.constructor, es.regexp.escape, es.regexp.exec, es.regexp.dot-all, es.regexp.flags, es.regexp.sticky, es.regexp.test and es.regexp.to-string.
class String {
static fromCodePoint(...codePoints: Array<number>): string;
static raw({ raw: ArrayLike<mixed> }, ...substitutions: Array<mixed>): string;
at(index: int): string | void;
includes(searchString: string, position?: number): boolean;
startsWith(searchString: string, position?: number): boolean;
endsWith(searchString: string, position?: number): boolean;
repeat(count: number): string;
padStart(length: number, fillStr?: string = ' '): string;
padEnd(length: number, fillStr?: string = ' '): string;
codePointAt(pos: number): number | void;
match(template: any): any; // ES2015+ fix for @@match support
matchAll<T>(matcher: { @@matchAll(input: string): T }): T;
matchAll(pattern?: string | RegExp): Iterator;
replace(template: any, replacer: any): any; // ES2015+ fix for @@replace support
replaceAll<T>(searchValue: { @@replace(input, replacement): T }, replacement: any): T;
replaceAll(searchValue: string | RegExp, replacement: string): string;
replaceAll(searchValue: string, replacer: (match, offset, input) => string): string;
replaceAll(searchValue: RegExp, replacer: (match, capture1, ..., captureN, offset, input, groups?) => string): string;
search(template: any): any; // ES2015+ fix for @@search support
split(separator: RegExp, limit?: int): Array<string | undefined>;
split<T>(separator: { @@split(input: string, limit?: int): T }, limit?: int): T; // ES2015+ fix for @@split support, some fixes for old engines
split(separator?: any, limit?: int): Array<string>;
trim(): string;
trimLeft(): string;
trimRight(): string;
trimStart(): string;
trimEnd(): string;
isWellFormed(): boolean;
toWellFormed(): string;
anchor(name: string): string;
big(): string;
blink(): string;
bold(): string;
fixed(): string;
fontcolor(color: string): string;
fontsize(size: any): string;
italics(): string;
link(url: string): string;
small(): string;
strike(): string;
sub(): string;
substr(start: int, length?: int): string;
sup(): string;
@@iterator(): Iterator<characters>;
}
class RegExp {
// support for sticky (`y`) flag, dotAll (`s`) flag, named capture groups, can alter flags
constructor(pattern: RegExp | string, flags?: string): RegExp;
static escape(value: string): string;
exec(string: string): Array<string | undefined> | null; // IE8 fixes
test(string: string): boolean; // delegation to `.exec`
toString(): string; // ES2015+ fix - generic
@@match(string: string): Array | null;
@@matchAll(string: string): Iterator;
@@replace(string: string, replaceValue: Function | string): string;
@@search(string: string): number;
@@split(string: string, limit?: number): Array<string | undefined>;
readonly attribute dotAll: boolean; // IE9+
readonly attribute flags: string; // IE9+
readonly attribute sticky: boolean; // IE9+
}
function escape(string: string): string;
function unescape(string: string): string;
core-js(-pure)/es|stable|actual|full/string
core-js(-pure)/es|stable|actual|full/string/virtual
core-js(-pure)/es|stable|actual|full/string/from-code-point
core-js(-pure)/es|stable|actual|full/string/raw
core-js/es|stable|actual|full/string/match
core-js/es|stable|actual|full/string/replace
core-js/es|stable|actual|full/string/search
core-js/es|stable|actual|full/string/split
core-js(-pure)/es|stable|actual/string(/virtual)/at
core-js(-pure)/es|stable|actual|full/string(/virtual)/code-point-at
core-js(-pure)/es|stable|actual|full/string(/virtual)/ends-with
core-js(-pure)/es|stable|actual|full/string(/virtual)/includes
core-js(-pure)/es|stable|actual|full/string(/virtual)/starts-with
core-js(-pure)/es|stable|actual|full/string(/virtual)/match-all
core-js(-pure)/es|stable|actual|full/string(/virtual)/pad-start
core-js(-pure)/es|stable|actual|full/string(/virtual)/pad-end
core-js(-pure)/es|stable|actual|full/string(/virtual)/repeat
core-js(-pure)/es|stable|actual|full/string(/virtual)/replace-all
core-js(-pure)/es|stable|actual|full/string(/virtual)/trim
core-js(-pure)/es|stable|actual|full/string(/virtual)/trim-start
core-js(-pure)/es|stable|actual|full/string(/virtual)/trim-end
core-js(-pure)/es|stable|actual|full/string(/virtual)/trim-left
core-js(-pure)/es|stable|actual|full/string(/virtual)/trim-right
core-js(-pure)/es|stable|actual|full/string(/virtual)/is-well-formed
core-js(-pure)/es|stable|actual|full/string(/virtual)/to-well-formed
core-js(-pure)/es|stable|actual|full/string(/virtual)/anchor
core-js(-pure)/es|stable|actual|full/string(/virtual)/big
core-js(-pure)/es|stable|actual|full/string(/virtual)/blink
core-js(-pure)/es|stable|actual|full/string(/virtual)/bold
core-js(-pure)/es|stable|actual|full/string(/virtual)/fixed
core-js(-pure)/es|stable|actual|full/string(/virtual)/fontcolor
core-js(-pure)/es|stable|actual|full/string(/virtual)/fontsize
core-js(-pure)/es|stable|actual|full/string(/virtual)/italics
core-js(-pure)/es|stable|actual|full/string(/virtual)/link
core-js(-pure)/es|stable|actual|full/string(/virtual)/small
core-js(-pure)/es|stable|actual|full/string(/virtual)/strike
core-js(-pure)/es|stable|actual|full/string(/virtual)/sub
core-js(-pure)/es|stable|actual|full/string(/virtual)/substr
core-js(-pure)/es|stable|actual|full/string(/virtual)/sup
core-js(-pure)/es|stable|actual|full/string(/virtual)/iterator
core-js/es|stable|actual|full/regexp
core-js/es|stable|actual|full/regexp/constructor
core-js(-pure)/es|stable|actual|full/regexp/escape
core-js/es|stable|actual|full/regexp/dot-all
core-js(-pure)/es|stable|actual|full/regexp/flags
core-js/es|stable|actual|full/regexp/match
core-js/es|stable|actual|full/regexp/replace
core-js/es|stable|actual|full/regexp/search
core-js/es|stable|actual|full/regexp/split
core-js/es|stable|actual|full/regexp/sticky
core-js/es|stable|actual|full/regexp/test
core-js/es|stable|actual|full/regexp/to-string
core-js/es|stable|actual|full/escape
core-js/es|stable|actual|full/unescape
for (let value of 'a𠮷b') {
console.log(value); // -> 'a', '𠮷', 'b'
}
'foobarbaz'.includes('bar'); // => true
'foobarbaz'.includes('bar', 4); // => false
'foobarbaz'.startsWith('foo'); // => true
'foobarbaz'.startsWith('bar', 3); // => true
'foobarbaz'.endsWith('baz'); // => true
'foobarbaz'.endsWith('bar', 6); // => true
'string'.repeat(3); // => 'stringstringstring'
'hello'.padStart(10); // => ' hello'
'hello'.padStart(10, '1234'); // => '12341hello'
'hello'.padEnd(10); // => 'hello '
'hello'.padEnd(10, '1234'); // => 'hello12341'
'𠮷'.codePointAt(0); // => 134071
String.fromCodePoint(97, 134071, 98); // => 'a𠮷b'
let name = 'Bob';
String.raw`Hi\n${ name }!`; // => 'Hi\\nBob!' (ES2015 template string syntax)
String.raw({ raw: 'test' }, 0, 1, 2); // => 't0e1s2t'
'foo'.bold(); // => '<b>foo</b>'
'bar'.anchor('a"b'); // => '<a name="a"b">bar</a>'
'baz'.link('https://example.com'); // => '<a href="https://example.com">baz</a>'
RegExp('.', 's').test('\n'); // => true
RegExp('.', 's').dotAll; // => true
RegExp('foo:(?<foo>\\w+),bar:(?<bar>\\w+)').exec('foo:abc,bar:def').groups; // => { foo: 'abc', bar: 'def' }
'foo:abc,bar:def'.replace(RegExp('foo:(?<foo>\\w+),bar:(?<bar>\\w+)'), '$<bar>,$<foo>'); // => 'def,abc'
RegExp(/./g, 'm'); // => /./m
/foo/.flags; // => ''
/foo/gi.flags; // => 'gi'
RegExp('foo', 'y').sticky; // => true
const text = 'First line\nSecond line';
const regex = RegExp('(?<index>\\S+) line\\n?', 'y');
regex.exec(text).groups.index; // => 'First'
regex.exec(text).groups.index; // => 'Second'
regex.exec(text); // => null
'foo'.match({ [Symbol.match]: () => 1 }); // => 1
'foo'.replace({ [Symbol.replace]: () => 2 }); // => 2
'foo'.search({ [Symbol.search]: () => 3 }); // => 3
'foo'.split({ [Symbol.split]: () => 4 }); // => 4
RegExp.prototype.toString.call({ source: 'foo', flags: 'bar' }); // => '/foo/bar'
' hello '.trimLeft(); // => 'hello '
' hello '.trimRight(); // => ' hello'
' hello '.trimStart(); // => 'hello '
' hello '.trimEnd(); // => ' hello'
for (let { groups: { number, letter } } of '1111a2b3cccc'.matchAll(RegExp('(?<number>\\d)(?<letter>\\D)', 'g'))) {
console.log(number, letter); // -> 1 a, 2 b, 3 c
}
'Test abc test test abc test.'.replaceAll('abc', 'foo'); // => 'Test foo test test foo test.'
'abc'.at(1); // => 'b'
'abc'.at(-1); // => 'c'
'a💩b'.isWellFormed(); // => true
'a\uD83Db'.isWellFormed(); // => false
'a💩b'.toWellFormed(); // => 'a💩b'
'a\uD83Db'.toWellFormed(); // => 'a�b'
RegExp.escape('10$'); // => '\\x310\\$'
RegExp.escape('abcdefg_123456'); // => '\\x61bcdefg_123456'
RegExp.escape('Привет'); // => 'Привет'
RegExp.escape('(){}[]|,.?*+-^$=<>\\/#&!%:;@~\'"`');
// => '\\(\\)\\{\\}\\[\\]\\|\\x2c\\.\\?\\*\\+\\x2d\\^\\$\\x3d\\x3c\\x3e\\\\\\/\\x23\\x26\\x21\\x25\\x3a\\x3b\\x40\\x7e\\x27\\x22\\x60'
RegExp.escape('\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF');
// => '\\t\\n\\v\\f\\r\\x20\\xa0\\u1680\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\u2028\\u2029\\ufeff'
RegExp.escape('💩'); // => '💩'
RegExp.escape('\uD83D'); // => '\\ud83d'
Modules es.number.constructor. The Number constructor supports binary and octal literals, examples:
Number('0b1010101'); // => 85
Number('0o7654321'); // => 2054353
Modules es.number.epsilon, es.number.is-finite, es.number.is-integer, es.number.is-nan, es.number.is-safe-integer, es.number.max-safe-integer, es.number.min-safe-integer, es.number.parse-float, es.number.parse-int, es.number.to-exponential, es.number.to-fixed, es.number.to-precision, es.parse-int, es.parse-float.
function Number(value?: any): number;
class Number {
constructor(value?: any): Number;
toExponential(digits?: number): string;
toFixed(digits?: number): string;
toPrecision(precision?: number): string;
static isFinite(number: any): boolean;
static isNaN(number: any): boolean;
static isInteger(number: any): boolean;
static isSafeInteger(number: any): boolean;
static parseFloat(string: string): number;
static parseInt(string: string, radix?: number): number;
static EPSILON: number;
static MAX_SAFE_INTEGER: number;
static MIN_SAFE_INTEGER: number;
}
function parseFloat(string: string): number;
function parseInt(string: string, radix?: number): number;
core-js(-pure)/es|stable|actual|full/number
core-js(-pure)/es|stable|actual|full/number/virtual
core-js(-pure)/es|stable|actual|full/number/constructor
core-js(-pure)/es|stable|actual|full/number/is-finite
core-js(-pure)/es|stable|actual|full/number/is-nan
core-js(-pure)/es|stable|actual|full/number/is-integer
core-js(-pure)/es|stable|actual|full/number/is-safe-integer
core-js(-pure)/es|stable|actual|full/number/parse-float
core-js(-pure)/es|stable|actual|full/number/parse-int
core-js(-pure)/es|stable|actual|full/number/epsilon
core-js(-pure)/es|stable|actual|full/number/max-safe-integer
core-js(-pure)/es|stable|actual|full/number/min-safe-integer
core-js(-pure)/es|stable|actual|full/number(/virtual)/to-exponential
core-js(-pure)/es|stable|actual|full/number(/virtual)/to-fixed
core-js(-pure)/es|stable|actual|full/number(/virtual)/to-precision
core-js(-pure)/es|stable|actual|full/parse-float
core-js(-pure)/es|stable|actual|full/parse-int
Modules es.math.acosh, es.math.asinh, es.math.atanh, es.math.cbrt, es.math.clz32, es.math.cosh, es.math.expm1, es.math.fround, es.math.f16round, es.math.hypot, es.math.imul, es.math.log10, es.math.log1p, es.math.log2, es.math.sign, es.math.sinh, es.math.sum-precise, es.math.tanh, es.math.trunc, es.math.to-string-tag.
namespace Math {
acosh(number: number): number;
asinh(number: number): number;
atanh(number: number): number;
cbrt(number: number): number;
clz32(number: number): number;
cosh(number: number): number;
expm1(number: number): number;
fround(number: number): number;
f16round(number: any): number;
hypot(...args: Array<number>): number;
imul(number1: number, number2: number): number;
log1p(number: number): number;
log10(number: number): number;
log2(number: number): number;
sign(number: number): 1 | -1 | 0 | -0 | NaN;
sinh(number: number): number;
sumPrecise(items: Iterable<number>): number;
tanh(number: number): number;
trunc(number: number): number;
@@toStringTag: 'Math';
}
core-js(-pure)/es|stable|actual|full/math
core-js(-pure)/es|stable|actual|full/math/acosh
core-js(-pure)/es|stable|actual|full/math/asinh
core-js(-pure)/es|stable|actual|full/math/atanh
core-js(-pure)/es|stable|actual|full/math/cbrt
core-js(-pure)/es|stable|actual|full/math/clz32
core-js(-pure)/es|stable|actual|full/math/cosh
core-js(-pure)/es|stable|actual|full/math/expm1
core-js(-pure)/es|stable|actual|full/math/fround
core-js(-pure)/es|stable|actual|full/math/f16round
core-js(-pure)/es|stable|actual|full/math/hypot
core-js(-pure)/es|stable|actual|full/math/imul
core-js(-pure)/es|stable|actual|full/math/log1p
core-js(-pure)/es|stable|actual|full/math/log10
core-js(-pure)/es|stable|actual|full/math/log2
core-js(-pure)/es|stable|actual|full/math/sign
core-js(-pure)/es|stable|actual|full/math/sinh
core-js(-pure)/es|stable|actual|full/math/sum-precise
core-js(-pure)/es|stable|actual|full/math/tanh
core-js(-pure)/es|stable|actual|full/math/trunc
core-js(-pure)/es|stable|actual|full/math/to-string-tag
1e20 + 0.1 + -1e20; // => 0
Math.sumPrecise([1e20, 0.1, -1e20]); // => 0.1
Modules es.date.to-string and es.date.to-primitive, ES5 features with fixes: es.date.now, es.date.to-iso-string and es.date.to-json.
Annex B methods. Modules es.date.get-year, es.date.set-year and es.date.to-gmt-string.
class Date {
getYear(): int;
setYear(year: int): number;
toGMTString(): string;
toISOString(): string;
toJSON(): string | null;
toString(): string;
@@toPrimitive(hint: 'default' | 'number' | 'string'): string | number;
static now(): number;
}
core-js/es|stable|actual|full/date
core-js/es|stable|actual|full/date/to-string
core-js(-pure)/es|stable|actual|full/date/now
core-js(-pure)/es|stable|actual|full/date/get-year
core-js(-pure)/es|stable|actual|full/date/set-year
core-js(-pure)/es|stable|actual|full/date/to-gmt-string
core-js(-pure)/es|stable|actual|full/date/to-iso-string
core-js(-pure)/es|stable|actual|full/date/to-json
core-js(-pure)/es|stable|actual|full/date/to-primitive
new Date(NaN).toString(); // => 'Invalid Date'
Modules es.promise, es.promise.all-settled, es.promise.any, es.promise.finally, es.promise.try and es.promise.with-resolvers.
class Promise {
constructor(executor: (resolve: Function, reject: Function) => void): Promise;
then(onFulfilled?: Function, onRejected?: Function): Promise;
catch(onRejected?: Function): Promise;
finally<T>(this: Promise<T>, onFinally?: any): Promise<T>;
static all(iterable: Iterable): Promise;
static allSettled(iterable: Iterable): Promise;
static any(promises: Iterable): Promise;
static race(iterable: Iterable): Promise;
static reject(r?: any): Promise;
static resolve(x?: any): Promise;
static try(callbackfn: Function, ...args: Array<mixed>): Promise;
static withResolvers(): { promise: Promise, resolve: Function, reject: Function };
}
core-js(-pure)/es|stable|actual|full/promise
core-js(-pure)/es|stable|actual|full/promise/all-settled
core-js(-pure)/es|stable|actual|full/promise/any
core-js(-pure)/es|stable|actual|full/promise/finally
core-js(-pure)/es|stable|actual|full/promise/try
core-js(-pure)/es|stable|actual|full/promise/with-resolvers
Basic examples:
function sleepRandom(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time * 1e3, 0 | Math.random() * 1e3);
});
}
console.log('Run'); // -> Run
sleepRandom(5).then(result => {
console.log(result); // -> 869, after 5 sec.
return sleepRandom(10);
}).then(result => {
console.log(result); // -> 202, after 10 sec.
}).then(() => {
console.log('immediately after'); // -> immediately after
throw new Error('Irror!');
}).then(() => {
console.log('will not be displayed');
}).catch(error => console.log(error)); // -> Error: Irror!
Promise.resolve and Promise.reject examples:
Promise.resolve(42).then(x => console.log(x)); // -> 42
Promise.reject(42).catch(error => console.log(error)); // -> 42
Promise.resolve($.getJSON('/data.json')); // => ES promise
Promise#finally examples:
Promise.resolve(42).finally(() => console.log('You will see it anyway'));
Promise.reject(42).finally(() => console.log('You will see it anyway'));
Promise.all examples:
Promise.all([
'foo',
sleepRandom(5),
sleepRandom(15),
sleepRandom(10), // after 15 sec:
]).then(x => console.log(x)); // -> ['foo', 956, 85, 382]
Promise.race examples:
function timeLimit(promise, time) {
return Promise.race([promise, new Promise((resolve, reject) => {
setTimeout(reject, time * 1e3, new Error(`Await > ${ time } sec`));
})]);
}
timeLimit(sleepRandom(5), 10).then(x => console.log(x)); // -> 853, after 5 sec.
timeLimit(sleepRandom(15), 10).catch(error => console.log(error)); // -> Error: Await > 10 sec
Promise.allSettled examples:
Promise.allSettled([
Promise.resolve(1),
Promise.reject(2),
Promise.resolve(3),
]).then(console.log); // -> [{ value: 1, status: 'fulfilled' }, { reason: 2, status: 'rejected' }, { value: 3, status: 'fulfilled' }]
Promise.any examples:
Promise.any([
Promise.resolve(1),
Promise.reject(2),
Promise.resolve(3),
]).then(console.log); // -> 1
Promise.any([
Promise.reject(1),
Promise.reject(2),
Promise.reject(3),
]).catch(({ errors }) => console.log(errors)); // -> [1, 2, 3]
Promise.try examples:
Promise.try(() => 42).then(it => console.log(`Promise, resolved as ${ it }`));
Promise.try(() => { throw new Error('42'); }).catch(error => console.log(`Promise, rejected as ${ error }`));
Promise.try(async () => 42).then(it => console.log(`Promise, resolved as ${ it }`));
Promise.try(async () => { throw new Error('42'); }).catch(error => console.log(`Promise, rejected as ${ error }`));
Promise.try(it => it, 42).then(it => console.log(`Promise, resolved as ${ it }`));
Promise.withResolvers examples:
const d = Promise.withResolvers();
d.resolve(42);
d.promise.then(console.log); // -> 42
Examples with async functions:
let delay = time => new Promise(resolve => setTimeout(resolve, time));
async function sleepRandom(time) {
await delay(time * 1e3);
return 0 | Math.random() * 1e3;
}
async function sleepError(time, msg) {
await delay(time * 1e3);
throw new Error(msg);
}
(async () => {
try {
console.log('Run'); // -> Run
console.log(await sleepRandom(5)); // -> 936, after 5 sec.
let [a, b, c] = await Promise.all([
sleepRandom(5),
sleepRandom(15),
sleepRandom(10),
]);
console.log(a, b, c); // -> 210 445 71, after 15 sec.
await sleepError(5, 'Error!');
console.log('Will not be displayed');
} catch (error) {
console.log(error); // -> Error: Error!, after 5 sec.
}
})();
In Node.js, as with the native implementation, the unhandledRejection and rejectionHandled events are available:
process.on('unhandledRejection', (reason, promise) => console.log('unhandled', reason, promise));
process.on('rejectionHandled', promise => console.log('handled', promise));
let promise = Promise.reject(42);
// -> unhandled 42 [object Promise]
setTimeout(() => promise.catch(() => { /* empty */ }), 1e3);
// -> handled [object Promise]
In a browser, an unhandled rejection is reported to the console by default; you can also add handlers for unhandled and later handled rejections, examples:
globalThis.addEventListener('unhandledrejection', e => console.log('unhandled', e.reason, e.promise));
globalThis.addEventListener('rejectionhandled', e => console.log('handled', e.reason, e.promise));
// or
globalThis.onunhandledrejection = e => console.log('unhandled', e.reason, e.promise);
globalThis.onrejectionhandled = e => console.log('handled', e.reason, e.promise);
let promise = Promise.reject(42);
// -> unhandled 42 [object Promise]
setTimeout(() => promise.catch(() => { /* empty */ }), 1e3);
// -> handled 42 [object Promise]
Modules es.symbol, es.symbol.async-dispose, es.symbol.async-iterator, es.symbol.description, es.symbol.dispose, es.symbol.has-instance, es.symbol.is-concat-spreadable, es.symbol.iterator, es.symbol.match, es.symbol.match-all, es.symbol.replace, es.symbol.search, es.symbol.species, es.symbol.split, es.symbol.to-primitive, es.symbol.to-string-tag, es.symbol.unscopables.
const Symbol: {
(description?): symbol;
prototype: {
readonly attribute description: string | void;
};
asyncDispose: @@asyncDispose;
asyncIterator: @@asyncIterator;
dispose: @@dispose;
hasInstance: @@hasInstance;
isConcatSpreadable: @@isConcatSpreadable;
iterator: @@iterator;
match: @@match;
matchAll: @@matchAll;
replace: @@replace;
search: @@search;
species: @@species;
split: @@split;
toPrimitive: @@toPrimitive;
toStringTag: @@toStringTag;
unscopables: @@unscopables;
for(key: string): symbol;
keyFor(sym: symbol): string | void;
useSimple(): void;
useSetter(): void;
};
class Object {
static getOwnPropertySymbols(object: any): Array<symbol>;
}
Some methods are also wrapped to work correctly with the Symbol polyfill.
class Object {
static create(prototype: Object | null, properties?: { [property: PropertyKey]: PropertyDescriptor }): Object;
static defineProperties(object: Object, properties: { [property: PropertyKey]: PropertyDescriptor }): Object;
static defineProperty(object: Object, property: PropertyKey, attributes: PropertyDescriptor): Object;
static getOwnPropertyDescriptor(object: any, property: PropertyKey): PropertyDescriptor | void;
static getOwnPropertyNames(object: any): Array<string>;
propertyIsEnumerable(key: PropertyKey): boolean;
}
core-js(-pure)/es|stable|actual|full/symbol
core-js(-pure)/es|stable|actual|full/symbol/async-dispose
core-js(-pure)/es|stable|actual|full/symbol/async-iterator
core-js/es|stable|actual|full/symbol/description
core-js(-pure)/es|stable|actual|full/symbol/dispose
core-js(-pure)/es|stable|actual|full/symbol/has-instance
core-js(-pure)/es|stable|actual|full/symbol/is-concat-spreadable
core-js(-pure)/es|stable|actual|full/symbol/iterator
core-js(-pure)/es|stable|actual|full/symbol/match
core-js(-pure)/es|stable|actual|full/symbol/match-all
core-js(-pure)/es|stable|actual|full/symbol/replace
core-js(-pure)/es|stable|actual|full/symbol/search
core-js(-pure)/es|stable|actual|full/symbol/species
core-js(-pure)/es|stable|actual|full/symbol/split
core-js(-pure)/es|stable|actual|full/symbol/to-primitive
core-js(-pure)/es|stable|actual|full/symbol/to-string-tag
core-js(-pure)/es|stable|actual|full/symbol/unscopables
core-js(-pure)/es|stable|actual|full/symbol/for
core-js(-pure)/es|stable|actual|full/symbol/key-for
core-js(-pure)/es|stable|actual|full/object/get-own-property-symbols
let Person = (() => {
let NAME = Symbol('name');
return class {
constructor(name) {
this[NAME] = name;
}
getName() {
return this[NAME];
}
};
})();
let person = new Person('Vasya');
person.getName(); // => 'Vasya'
person.name; // => undefined
person[Symbol('name')]; // => undefined, symbols are unique
for (let key in person) console.log(key); // -> nothing, for-in skips symbol keys
Symbol.for & Symbol.keyFor examples:
let symbol = Symbol.for('key');
symbol === Symbol.for('key'); // => true
Symbol.keyFor(symbol); // => 'key'
Examples with methods for getting own object keys:
let object = { a: 1 };
Object.defineProperty(object, 'b', { value: 2 });
object[Symbol('c')] = 3;
Object.keys(object); // => ['a']
Object.getOwnPropertyNames(object); // => ['a', 'b']
Object.getOwnPropertySymbols(object); // => [Symbol(c)]
Reflect.ownKeys(object); // => ['a', 'b', Symbol(c)]
Symbol('foo').description; // => 'foo'
Symbol().description; // => undefined
Symbol polyfill:⬆Symbol returns an object.Symbol.for and Symbol.keyFor can't be polyfilled cross-realm.Symbol polyfill defines a setter in Object.prototype. For this reason, an uncontrolled creation of symbols can cause a memory leak and the in operator does not work correctly with the Symbol polyfill: Symbol() in {} // => true.You can disable defining setters in Object.prototype. Examples:
Symbol.useSimple();
let object1 = { [Symbol('symbol1')]: true };
for (let key in object1) console.log(key); // -> 'Symbol(symbol1)_t.qamkg9f3q', without native `Symbol`
Symbol.useSetter();
let object2 = { [Symbol('symbol2')]: true };
for (let key in object2) console.log(key); // -> nothing
core-js does not add setters to Object.prototype for well-known symbols, so that something like Symbol.iterator in foo works correctly. It can cause problems with their enumerability.localStorage).core-js uses native collections in most cases and only fixes methods / constructors where required; in old environments, it uses a fast polyfill (O(1) lookup).
Modules es.map, es.map.group-by, es.map.get-or-insert and es.map.get-or-insert-computed.
class Map {
constructor(iterable?: Iterable<[key, value]>): Map;
clear(): void;
delete(key: any): boolean;
forEach(callbackfn: (value: any, key: any, target: any) => void, thisArg?: any): void;
get(key: any): any;
getOrInsert(key: any, value: any): any;
getOrInsertComputed(key: any, callbackfn: (key: any) => any): any;
has(key: any): boolean;
set(key: any, val: any): this;
values(): Iterator<value>;
keys(): Iterator<key>;
entries(): Iterator<[key, value]>;
@@iterator(): Iterator<[key, value]>;
readonly attribute size: number;
static groupBy(items: Iterable, callbackfn: (value: any, index: number) => key): Map<key, Array<mixed>>;
}
core-js(-pure)/es|stable|actual|full/map
core-js(-pure)/es|stable|actual|full/map/group-by
core-js(-pure)/es|stable|actual|full/map/get-or-insert
core-js(-pure)/es|stable|actual|full/map/get-or-insert-computed
let array = [1];
let map = new Map([['a', 1], [42, 2]]);
map.set(array, 3).set(true, 4);
map.size; // => 4
map.has(array); // => true
map.has([1]); // => false
map.get(array); // => 3
map.forEach((val, key) => {
console.log(val); // -> 1, 2, 3, 4
console.log(key); // -> 'a', 42, [1], true
});
map.delete(array);
map.size; // => 3
map.get(array); // => undefined
Array.from(map); // => [['a', 1], [42, 2], [true, 4]]
map = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of map) {
console.log(key); // -> 'a', 'b', 'c'
console.log(value); // -> 1, 2, 3
}
for (let value of map.values()) console.log(value); // -> 1, 2, 3
for (let key of map.keys()) console.log(key); // -> 'a', 'b', 'c'
for (let [key, value] of map.entries()) {
console.log(key); // -> 'a', 'b', 'c'
console.log(value); // -> 1, 2, 3
}
map = Map.groupBy([1, 2, 3, 4, 5], it => it % 2);
map.get(1); // => [1, 3, 5]
map.get(0); // => [2, 4]
map = new Map([['a', 1]]);
map.getOrInsert('a', 2); // => 1
map.getOrInsert('b', 3); // => 3
map.getOrInsertComputed('a', key => key); // => 1
map.getOrInsertComputed('c', key => key); // => 'c'
map; // => Map { 'a' => 1, 'b' => 3, 'c' => 'c' }
Modules es.set, es.set.difference.v2, es.set.intersection.v2, es.set.is-disjoint-from.v2, es.set.is-subset-of.v2, es.set.is-superset-of.v2, es.set.symmetric-difference.v2, es.set.union.v2.
class Set {
constructor(iterable?: Iterable<value>): Set;
add(key: any): this;
clear(): void;
delete(key: any): boolean;
forEach(callbackfn: (value: any, key: any, target: any) => void, thisArg?: any): void;
has(key: any): boolean;
values(): Iterator<value>;
keys(): Iterator<value>;
entries(): Iterator<[value, value]>;
difference(other: SetLike<mixed>): Set;
intersection(other: SetLike<mixed>): Set;
isDisjointFrom(other: SetLike<mixed>): boolean;
isSubsetOf(other: SetLike<mixed>): boolean;
isSupersetOf(other: SetLike<mixed>): boolean;
symmetricDifference(other: SetLike<mixed>): Set;
union(other: SetLike<mixed>): Set;
@@iterator(): Iterator<value>;
readonly attribute size: number;
}
core-js(-pure)/es|stable|actual|full/set
core-js(-pure)/es|stable|actual|full/set/difference
core-js(-pure)/es|stable|actual|full/set/intersection
core-js(-pure)/es|stable|actual|full/set/is-disjoint-from
core-js(-pure)/es|stable|actual|full/set/is-subset-of
core-js(-pure)/es|stable|actual|full/set/is-superset-of
core-js(-pure)/es|stable|actual|full/set/symmetric-difference
core-js(-pure)/es|stable|actual|full/set/union
let set = new Set(['a', 'b', 'a', 'c']);
set.add('d').add('b').add('e');
set.size; // => 5
set.has('b'); // => true
set.forEach(it => {
console.log(it); // -> 'a', 'b', 'c', 'd', 'e'
});
set.delete('b');
set.size; // => 4
set.has('b'); // => false
Array.from(set); // => ['a', 'c', 'd', 'e']
set = new Set([1, 2, 3, 2, 1]);
for (let value of set) console.log(value); // -> 1, 2, 3
for (let value of set.values()) console.log(value); // -> 1, 2, 3
for (let key of set.keys()) console.log(key); // -> 1, 2, 3
for (let [key, value] of set.entries()) {
console.log(key); // -> 1, 2, 3
console.log(value); // -> 1, 2, 3
}
new Set([1, 2, 3]).union(new Set([3, 4, 5])); // => Set { 1, 2, 3, 4, 5 }
new Set([1, 2, 3]).intersection(new Set([3, 4, 5])); // => Set { 3 }
new Set([1, 2, 3]).difference(new Set([3, 4, 5])); // => Set { 1, 2 }
new Set([1, 2, 3]).symmetricDifference(new Set([3, 4, 5])); // => Set { 1, 2, 4, 5 }
new Set([1, 2, 3]).isDisjointFrom(new Set([4, 5, 6])); // => true
new Set([1, 2, 3]).isSubsetOf(new Set([5, 4, 3, 2, 1])); // => true
new Set([5, 4, 3, 2, 1]).isSupersetOf(new Set([1, 2, 3])); // => true
Modules es.weak-map, es.weak-map.get-or-insert and es.weak-map.get-or-insert-computed.
class WeakMap {
constructor(iterable?: Iterable<[object | nonRegisteredSymbol, value]>): WeakMap;
delete(key: object | symbol): boolean;
get(key: object | symbol): value | undefined;
getOrInsert(key: object | nonRegisteredSymbol, value: any): any;
getOrInsertComputed(key: object | nonRegisteredSymbol, callbackfn: (key: any) => any): any;
has(key: object | symbol): boolean;
set(key: object | nonRegisteredSymbol, val: any): this;
}
core-js(-pure)/es|stable|actual|full/weak-map
core-js(-pure)/es|stable|actual|full/weak-map/get-or-insert
core-js(-pure)/es|stable|actual|full/weak-map/get-or-insert-computed
let a = [1];
let b = [2];
let c = [3];
let weakmap = new WeakMap([[a, 1], [b, 2]]);
weakmap.set(c, 3).set(b, 4);
weakmap.has(a); // => true
weakmap.has([1]); // => false
weakmap.get(a); // => 1
weakmap.delete(a);
weakmap.get(a); // => undefined
// Private properties store:
let Person = (() => {
let names = new WeakMap();
return class {
constructor(name) {
names.set(this, name);
}
getName() {
return names.get(this);
}
};
})();
let person = new Person('Vasya');
person.getName(); // => 'Vasya'
Modules es.weak-set.
class WeakSet {
constructor(iterable?: Iterable<object | nonRegisteredSymbol>): WeakSet;
add(key: object | nonRegisteredSymbol): this;
delete(key: object | symbol): boolean;
has(key: object | symbol): boolean;
}
core-js(-pure)/es|stable|actual|full/weak-set
let a = [1];
let b = [2];
let c = [3];
let weakset = new WeakSet([a, b, a]);
weakset.add(c).add(b).add(c);
weakset.has(b); // => true
weakset.has([2]); // => false
weakset.delete(b);
weakset.has(b); // => false
[!WARNING]
- Weak-collections polyfill stores values as hidden properties of keys. It works correctly and does not leak in most cases. However, it is desirable to store a collection longer than its keys.
- Native symbols as
WeakMapkeys can't be properly polyfilled without memory leaks.
[!NOTE] These are only built-ins for Explicit Resource Management; the
usingsyntax requires transpiler support.
[!WARNING] To add
@@asyncDisposeto async generators, the global polyfill needs access to%AsyncIteratorPrototype%. If the engine does not exposeAsyncIterator, setUSE_FUNCTION_CONSTRUCTORtotrueor pass the prototype asAsyncIteratorPrototypetocore-js/configuratorbefore loading the polyfill. SeeAsyncIteratorhelpers caveats.
Modules es.disposable-stack.constructor, es.iterator.dispose, es.async-disposable-stack.constructor, es.async-iterator.async-dispose, es.suppressed-error.constructor, es.symbol.async-dispose, es.symbol.dispose.
class Symbol {
static asyncDispose: @@asyncDispose;
static dispose: @@dispose;
}
class DisposableStack {
constructor(): DisposableStack;
readonly attribute disposed: boolean;
dispose(): undefined;
use(value: Disposable | null | undefined): value;
adopt(value: any, onDispose: Function): value;
defer(onDispose: Function): undefined;
move(): DisposableStack;
@@dispose(): undefined;
@@toStringTag: 'DisposableStack';
}
class AsyncDisposableStack {
constructor(): AsyncDisposableStack;
readonly attribute disposed: boolean;
disposeAsync(): Promise<undefined>;
use(value: AsyncDisposable | Disposable | null | undefined): value;
adopt(value: any, onDispose: Function): value;
defer(onDispose: Function): undefined;
move(): AsyncDisposableStack;
@@asyncDispose(): Promise<undefined>;
@@toStringTag: 'AsyncDisposableStack';
}
class SuppressedError extends Error {
constructor(error: any, suppressed: any, message?: string): SuppressedError;
error: any;
suppressed: any;
message: string;
}
class Iterator {
@@dispose(): undefined;
}
class AsyncIterator {
@@asyncDispose(): Promise<undefined>;
}
core-js(-pure)/es|stable|actual|full/disposable-stack
core-js(-pure)/es|stable|actual|full/disposable-stack/constructor
core-js(-pure)/es|stable|actual|full/async-disposable-stack
core-js(-pure)/es|stable|actual|full/async-disposable-stack/constructor
core-js(-pure)/es|stable|actual|full/iterator/dispose
core-js/es|stable/async-iterator
core-js/es|stable/async-iterator/async-dispose
core-js(-pure)/actual|full/async-iterator
core-js(-pure)/actual|full/async-iterator/async-dispose
core-js(-pure)/es|stable|actual|full/suppressed-error
core-js(-pure)/es|stable|actual|full/symbol/async-dispose
core-js(-pure)/es|stable|actual|full/symbol/dispose
const stack = new DisposableStack();
stack.use({
[Symbol.dispose]() {
console.log('resource disposed');
},
});
stack.defer(() => console.log('deferred cleanup'));
stack.adopt(42, value => console.log(`${ value } released`));
stack.disposed; // => false
stack.dispose(); // -> '42 released', 'deferred cleanup', 'resource disposed'
stack.disposed; // => true
const failing = new DisposableStack();
failing.defer(() => {
throw new Error('first');
});
failing.defer(() => {
throw new Error('second');
});
try {
failing.dispose();
} catch (error) {
error instanceof SuppressedError; // => true
error.error.message; // => 'first'
error.suppressed.message; // => 'second'
}
const asyncStack = new AsyncDisposableStack();
asyncStack.defer(async () => console.log('async cleanup'));
await asyncStack.disposeAsync(); // -> 'async cleanup'
function * gen() {
try {
yield 1;
} finally {
console.log('iterator closed');
}
}
const iterator = gen();
iterator.next();
iterator[Symbol.dispose](); // -> 'iterator closed'
Implementations and fixes for ArrayBuffer, DataView, Typed Arrays constructors, static and prototype methods. Typed arrays work only in environments with support for descriptors (IE9+), ArrayBuffer and DataView should work anywhere.
Modules es.array-buffer.constructor, es.array-buffer.is-view, es.array-buffer.detached, es.array-buffer.slice, es.array-buffer.transfer, es.array-buffer.transfer-to-fixed-length, es.data-view, es.data-view.get-float16, es.data-view.set-float16, es.typed-array.int8-array, es.typed-array.uint8-array, es.typed-array.uint8-clamped-array, es.typed-array.int16-array, es.typed-array.uint16-array, es.typed-array.int32-array, es.typed-array.uint32-array, es.typed-array.float32-array, es.typed-array.float64-array, es.typed-array.copy-within, es.typed-array.every, es.typed-array.fill, es.typed-array.filter, es.typed-array.find, es.typed-array.find-index, es.typed-array.find-last, es.typed-array.find-last-index, es.typed-array.for-each, es.typed-array.from, es.typed-array.includes, es.typed-array.index-of, es.typed-array.iterator, es.typed-array.join, es.typed-array.last-index-of, es.typed-array.map, es.typed-array.of, es.typed-array.reduce, es.typed-array.reduce-right, es.typed-array.reverse, es.typed-array.set, es.typed-array.slice, es.typed-array.some, es.typed-array.sort, es.typed-array.subarray, es.typed-array.to-locale-string, es.typed-array.to-string, es.typed-array.at, es.typed-array.to-reversed, es.typed-array.to-sorted, es.typed-array.with, es.uint8-array.from-base64, es.uint8-array.from-hex, es.uint8-array.set-from-base64, es.uint8-array.set-from-hex, es.uint8-array.to-base64, es.uint8-array.to-hex.
class ArrayBuffer {
constructor(length?: any): ArrayBuffer;
readonly attribute byteLength: number;
readonly attribute detached: boolean;
slice(start?: any, end?: any): ArrayBuffer;
transfer(newLength?: number): ArrayBuffer;
transferToFixedLength(newLength?: number): ArrayBuffer;
static isView(arg: any): boolean;
}
class DataView {
constructor(buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
getInt8(offset: any): int8;
getUint8(offset: any): uint8;
getInt16(offset: any, littleEndian?: boolean = false): int16;
getUint16(offset: any, littleEndian?: boolean = false): uint16;
getInt32(offset: any, littleEndian?: boolean = false): int32;
getUint32(offset: any, littleEndian?: boolean = false): uint32;
getFloat16(offset: any, littleEndian?: boolean = false): float16;
getFloat32(offset: any, littleEndian?: boolean = false): float32;
getFloat64(offset: any, littleEndian?: boolean = false): float64;
setInt8(offset: any, value: any): void;
setUint8(offset: any, value: any): void;
setInt16(offset: any, value: any, littleEndian?: boolean = false): void;
setUint16(offset: any, value: any, littleEndian?: boolean = false): void;
setInt32(offset: any, value: any, littleEndian?: boolean = false): void;
setUint32(offset: any, value: any, littleEndian?: boolean = false): void;
setFloat16(offset: any, value: any, littleEndian?: boolean = false): void;
setFloat32(offset: any, value: any, littleEndian?: boolean = false): void;
setFloat64(offset: any, value: any, littleEndian?: boolean = false): void;
readonly attribute buffer: ArrayBuffer;
readonly attribute byteLength: number;
readonly attribute byteOffset: number;
}
class [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array,
] extends %TypedArray% {
constructor(length?: number): %TypedArray%;
constructor(object: %TypedArray% | Iterable | ArrayLike): %TypedArray%;
constructor(buffer: ArrayBuffer, byteOffset?: number, length?: number): %TypedArray%;
BYTES_PER_ELEMENT: number;
static BYTES_PER_ELEMENT: number;
}
class %TypedArray% {
// element is bigint for BigInt64Array and BigUint64Array, and number for other typed arrays.
at(index: int): number | bigint | void;
copyWithin(target: number, start: number, end?: number): this;
entries(): Iterator<[index, value]>;
every(callbackfn: (value: element, index: number, target: %TypedArray%) => boolean, thisArg?: any): boolean;
fill(value: element, start?: number, end?: number): this;
filter(callbackfn: (value: element, index: number, target: %TypedArray%) => boolean, thisArg?: any): %TypedArray%;
find(callbackfn: (value: element, index: number, target: %TypedArray%) => boolean, thisArg?: any): any;
findIndex(callbackfn: (value: element, index: number, target: %TypedArray%) => boolean, thisArg?: any): number;
findLast(callbackfn: (value: any, index: number, target: %TypedArray%) => boolean, thisArg?: any): any;
findLastIndex(callbackfn: (value: any, index: number, target: %TypedArray%) => boolean, thisArg?: any): number;
forEach(callbackfn: (value: element, index: number, target: %TypedArray%) => void, thisArg?: any): void;
includes(searchElement: any, from?: number): boolean;
indexOf(searchElement: any, from?: number): number;
join(separator: string = ','): string;
keys(): Iterator<index>;
lastIndexOf(searchElement: any, from?: number): number;
map(mapFn: (value: element, index: number, target: %TypedArray%) => element, thisArg?: any): %TypedArray%;
reduce(callbackfn: (memo: any, value: element, index: number, target: %TypedArray%) => any, initialValue?: any): any;
reduceRight(callbackfn: (memo: any, value: element, index: number, target: %TypedArray%) => any, initialValue?: any): any;
reverse(): this;
set(array: ArrayLike, offset?: number): void;
slice(start?: number, end?: number): %TypedArray%;
some(callbackfn: (value: element, index: number, target: %TypedArray%) => boolean, thisArg?: any): boolean;
sort(comparefn?: (a: element, b: element) => number): this; // with modern behavior like stable sort
subarray(begin?: number, end?: number): %TypedArray%;
toReversed(): %TypedArray%;
toSorted(comparefn?: (a: any, b: any) => number): %TypedArray%;
toString(): string;
toLocaleString(): string;
values(): Iterator<value>;
with(index: int, value: any): %TypedArray%;
@@iterator(): Iterator<value>;
readonly attribute buffer: ArrayBuffer;
readonly attribute byteLength: number;
readonly attribute byteOffset: number;
readonly attribute length: number;
static from(items: Iterable | ArrayLike, mapFn?: (value: any, index: number) => any, thisArg?: any): %TypedArray%;
static of(...args: Array<mixed>): %TypedArray%;
}
class Uint8Array {
static fromBase64(string: string, options?: { alphabet?: 'base64' | 'base64url', lastChunkHandling?: 'loose' | 'strict' | 'stop-before-partial' }): Uint8Array;
static fromHex(string: string): Uint8Array;
setFromBase64(string: string, options?: { alphabet?: 'base64' | 'base64url', lastChunkHandling?: 'loose' | 'strict' | 'stop-before-partial' }): { read: uint, written: uint };
setFromHex(string: string): { read: uint, written: uint };
toBase64(options?: { alphabet?: 'base64' | 'base64url', omitPadding?: boolean }): string;
toHex(): string;
}
core-js/es|stable|actual|full/array-buffer
core-js/es|stable|actual|full/array-buffer/constructor
core-js/es|stable|actual|full/array-buffer/is-view
core-js/es|stable|actual|full/array-buffer/detached
core-js/es|stable|actual|full/array-buffer/slice
core-js/es|stable|actual|full/array-buffer/transfer
core-js/es|stable|actual|full/array-buffer/transfer-to-fixed-length
core-js/es|stable|actual|full/data-view
core-js/es|stable|actual|full/data-view/get-float16
core-js/es|stable|actual|full/data-view/set-float16
core-js/es|stable|actual|full/typed-array
core-js/es|stable|actual|full/typed-array/int8-array
core-js/es|stable|actual|full/typed-array/uint8-array
core-js/es|stable|actual|full/typed-array/uint8-clamped-array
core-js/es|stable|actual|full/typed-array/int16-array
core-js/es|stable|actual|full/typed-array/uint16-array
core-js/es|stable|actual|full/typed-array/int32-array
core-js/es|stable|actual|full/typed-array/uint32-array
core-js/es|stable|actual|full/typed-array/float32-array
core-js/es|stable|actual|full/typed-array/float64-array
core-js/es|stable|actual|full/typed-array/methods
core-js/es|stable|actual|full/typed-array/at
core-js/es|stable|actual|full/typed-array/copy-within
core-js/es|stable|actual|full/typed-array/entries
core-js/es|stable|actual|full/typed-array/every
core-js/es|stable|actual|full/typed-array/fill
core-js/es|stable|actual|full/typed-array/filter
core-js/es|stable|actual|full/typed-array/find
core-js/es|stable|actual|full/typed-array/find-index
core-js/es|stable|actual|full/typed-array/find-last
core-js/es|stable|actual|full/typed-array/find-last-index
core-js/es|stable|actual|full/typed-array/for-each
core-js/es|stable|actual|full/typed-array/from
core-js/es|stable|actual|full/typed-array/from-base64
core-js/es|stable|actual|full/typed-array/from-hex
core-js/es|stable|actual|full/typed-array/includes
core-js/es|stable|actual|full/typed-array/index-of
core-js/es|stable|actual|full/typed-array/iterator
core-js/es|stable|actual|full/typed-array/join
core-js/es|stable|actual|full/typed-array/keys
core-js/es|stable|actual|full/typed-array/last-index-of
core-js/es|stable|actual|full/typed-array/map
core-js/es|stable|actual|full/typed-array/of
core-js/es|stable|actual|full/typed-array/reduce
core-js/es|stable|actual|full/typed-array/reduce-right
core-js/es|stable|actual|full/typed-array/reverse
core-js/es|stable|actual|full/typed-array/set
core-js/es|stable|actual|full/typed-array/set-from-base64
core-js/es|stable|actual|full/typed-array/set-from-hex
core-js/es|stable|actual|full/typed-array/slice
core-js/es|stable|actual|full/typed-array/some
core-js/es|stable|actual|full/typed-array/sort
core-js/es|stable|actual|full/typed-array/subarray
core-js/es|stable|actual|full/typed-array/to-base64
core-js/es|stable|actual|full/typed-array/to-hex
core-js/es|stable|actual|full/typed-array/to-locale-string
core-js/es|stable|actual|full/typed-array/to-reversed
core-js/es|stable|actual|full/typed-array/to-sorted
core-js/es|stable|actual|full/typed-array/to-string
core-js/es|stable|actual|full/typed-array/values
core-js/es|stable|actual|full/typed-array/with
new Int32Array(4); // => [0, 0, 0, 0]
new Uint8ClampedArray([1, 2, 3, 666]); // => [1, 2, 3, 255]
new Float32Array(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
let buffer = new ArrayBuffer(8);
let view = new DataView(buffer);
view.setFloat64(0, 123.456, true);
new Uint8Array(buffer.slice(4)); // => [47, 221, 94, 64]
Int8Array.of(1, 1.5, 5.7, 745); // => [1, 1, 5, -23]
Uint8Array.from([1, 1.5, 5.7, 745]); // => [1, 1, 5, 233]
let typed = new Uint8Array([1, 2, 3]);
let a = typed.slice(1); // => [2, 3]
typed.buffer === a.buffer; // => false
let b = typed.subarray(1); // => [2, 3]
typed.buffer === b.buffer; // => true
typed.filter(it => it % 2); // => [1, 3]
typed.map(it => it * 1.5); // => [1, 3, 4]
for (let value of typed) console.log(value); // -> 1, 2, 3
for (let value of typed.values()) console.log(value); // -> 1, 2, 3
for (let key of typed.keys()) console.log(key); // -> 0, 1, 2
for (let [key, value] of typed.entries()) {
console.log(key); // -> 0, 1, 2
console.log(value); // -> 1, 2, 3
}
new Int32Array([1, 2, 3]).at(1); // => 2
new Int32Array([1, 2, 3]).at(-1); // => 3
buffer = Int8