What is es6-shim?
The es6-shim package is designed to provide compatibility shims so that legacy JavaScript engines behave as closely as possible to ECMAScript 6 (ES6). It includes shims for new methods and functions introduced in ES6, allowing developers to use these features in environments that do not yet support them natively.
What are es6-shim's main functionalities?
Array.prototype methods
Adds new methods to Array.prototype like find, findIndex, etc., enabling more expressive operations on arrays.
[1, 2, 3].find(x => x == 2)
String.prototype methods
Introduces new String methods such as startsWith, endsWith, and includes for easier string manipulation.
'hello'.startsWith('hell')
Number properties
Provides new static properties and methods on the Number object like isNaN and isFinite for improved number checking.
Number.isNaN(NaN)
Promises
Implements Promises for asynchronous programming, following the ES6 specification.
new Promise(function(resolve, reject) { resolve(42); })
Maps and Sets
Adds support for new collection types such as Map and Set, offering more options for data storage and manipulation.
new Map([[1, 'one'], [2, 'two']])
Other packages similar to es6-shim
core-js
A modular standard library for JavaScript, including polyfills for ECMAScript up to 2021. Offers broader coverage than es6-shim, including proposals not yet standardized.
babel-polyfill
Part of Babel, this package includes a custom regenerator runtime and core-js. It's more comprehensive but has been deprecated in favor of directly including core-js and the regenerator-runtime.
es5-shim
Focuses on ensuring ECMAScript 5 compatibility, providing shims for older JavaScript engines. It's more focused on ES5, making it complementary rather than directly comparable to es6-shim.
ES6 Shim
Provides compatibility shims so that legacy JavaScript engines behave as
closely as possible to ECMAScript 6 (Harmony).
HTML version of the final ECMAScript 6 spec
Installation
If you want to use it in browser:
- Just include es6-shim before your scripts.
- Include es5-shim especially if your browser doesn't support ECMAScript 5 - but every JS engine requires the
es5-shim
to correct broken implementations, so it's strongly recommended to always include it.
For node.js
, io.js
, or any npm
-managed workflow (this is the recommended method):
npm install es6-shim
Alternative methods:
component install paulmillr/es6-shim
if you’re using component(1).bower install es6-shim
if you’re using Bower.
In both browser and node you may also want to include unorm
; see the String.prototype.normalize
section for details.
Safe shims
Map
, Set
(requires ES5 property descriptor support)Promise
String
:
String.prototype
:
RegExp
:
new RegExp
, when given a RegExp as the pattern, will no longer throw when given a "flags" string argument. (requires ES5)
RegExp.prototype
:
Number
:
- binary and octal literals:
Number('0b1')
and Number('0o7')
EPSILON
MAX_SAFE_INTEGER
MIN_SAFE_INTEGER
isNaN()
(a standalone shim is also available)isInteger()
isSafeInteger()
isFinite()
parseInt()
parseFloat()
Array
:
Array.prototype
:
Object
:
Math
:
acosh()
asinh()
atanh()
cbrt()
clz32()
cosh()
expm1()
fround()
hypot()
imul()
log10()
log1p()
log2()
sign()
sinh()
tanh()
trunc()
Math functions’ accuracy is 1e-11.
-
Reflect
apply()
construct()
defineProperty()
deleteProperty()
enumerate()
get()
getOwnPropertyDescriptor()
getPrototypeOf()
has()
isExtensible()
ownKeys()
preventExtensions()
set()
setPrototypeOf()
-
String.prototype
Annex B HTML methods
These methods are part of "Annex B", which means that although they are a defacto standard, you shouldn't use them. None the less, the es6-shim
provides them:
anchor()
big()
blink()
bold()
fixed()
fontcolor()
fontsize()
italics()
link()
small()
strike()
sub()
sup()
Subclassing
The Map
, Set
, and Promise
implementations are subclassable.
You should use the following pattern to create a subclass in ES5 which will continue to work in ES6:
require('es6-shim');
function MyPromise(exec) {
var promise = new Promise(exec);
Object.setPrototypeOf(promise, MyPromise.prototype);
return promise;
}
Object.setPrototypeOf(MyPromise, Promise);
MyPromise.prototype = Object.create(Promise.prototype, {
constructor: { value: MyPromise }
});
String.prototype.normalize
Including a proper shim for String.prototype.normalize
would increase the size of this library by a factor of more than 4.
So instead we recommend that you install the unorm
package alongside es6-shim
if you need String.prototype.normalize
.
See https://github.com/paulmillr/es6-shim/issues/134 for more discussion.
WeakMap shim
It is not possible to implement WeakMap in pure javascript.
The es6-collections implementation doesn't hold values strongly, which is critical for the collection. es6-shim
decided to not include an incorrect shim.
WeakMap
has very unusual use-cases, so you probably won't need it at all (use simple Map
instead).
Getting started
require('es6-shim');
var assert = require('assert');
assert.equal(true, 'abc'.startsWith('a'));
assert.equal(false, 'abc'.endsWith('a'));
assert.equal(true, 'john alice'.includes('john'));
assert.equal('123'.repeat(2), '123123');
assert.equal(false, NaN === NaN);
assert.equal(true, Object.is(NaN, NaN));
assert.equal(true, -0 === 0);
assert.equal(false, Object.is(-0, 0));
var result = Object.assign({ a: 1 }, { b: 2 });
assert.deepEqual(result, { a: 1, b: 2 });
assert.equal(true, isNaN('a'));
assert.equal(false, Number.isNaN('a'));
assert.equal(true, Number.isNaN(NaN));
assert.equal(true, isFinite('123'));
assert.equal(false, Number.isFinite('123'));
assert.equal(false, Number.isFinite(Infinity));
assert.equal(false, Number.isInteger(2.4));
assert.equal(1, Math.sign(400));
assert.equal(0, Math.sign(0));
assert.equal(-1, Math.sign(-400));
var found = [5, 10, 15, 10].find(function (item) { return item / 2 === 5; });
assert.equal(10, found);
var foundIndex = [5, 10, 15, 10].findIndex(function (item) { return item / 2 === 5; });
assert.equal(1, foundIndex);
var map = new Map([['Bob', 42], ['Foo', 'bar']]);
map.set('John', 25);
map.set('Alice', 400);
map.set(['meh'], 555);
assert.equal(undefined, map.get(['meh']));
map.delete('Alice');
map.keys();
map.values();
assert.equal(4, map.size);
var set = new Set([0, 1]);
set.add(2);
set.add(5);
assert.equal(true, set.has(0));
assert.equal(true, set.has(1));
assert.equal(true, set.has(2));
assert.equal(false, set.has(4));
assert.equal(true, set.has(5));
set.delete(5);
assert.equal(false, set.has(5));
Promise.resolve(5).then(function (value) {
assert.equal(value, 5);
if (value) throw new Error('whoops!');
return anotherPromise();
}).catch(function (e) {
assert.equal(e.message, 'whoops!');
assert.equal(true, e instanceof Error);
});
Caveats
Object.setPrototypeOf
/ Reflect.setPrototypeOf
- Note that null objects (
Object.create(null)
, eg, an object with null
as its [[Prototype]]
) can not have their [[Prototype]]
changed except via a native Object.setPrototypeOf
.