ES10 for 2020
First off, let's be clear- ECMAScript 2019 is ES10. Β We're excited for ES11, but we're not there yet. It's time for ES10. Here we go, let's see some code.
globalThis // <-- AMAZING for NPM
Array.prototype.flat
Array.prototype.flatMap // Love it!
Object.fromEntries // not to be confused with Object.entries
String.prototype.matchAll // Way better regex results.
String.prototype.trimStart/trimEnd // Renamed from trimLeft, trimRight
/*
And some syntax updates:
- Optional Try/Catch err param
- Optional number seperator '_' (similar to a comma)
*/
New Methods
Array.prototype.flat
// Flat works only on the first nested layer.
const EMOJIS = [
'π',
['π', 'π'],
[['π²', 'π±']],
[[['π¦', 'π¦']]],
[[[['β°']]]],
];
// Flat by default flattens only one layer down.
EMOJIS.flat().flat().flat().flat();
> (9)Β ["π", "π", "π", "π²", "π±", "π¦", "π¦", "β°"]
// Thankfully you can flatten infinitly.
EMOJIS.flat(Infinity)
> (9)Β ["π", "π", "π", "π²", "π±", "π¦", "π¦", "β°"]
Array.prototype.flatMap
FlatMap is nothing new, but I'd consider it much more useful. As implied, flatMap is the same as calling arr.map().flat()
, great for picking items from nested objects.
const SENTENCES = [
'Hello world',
'Goodbye world',
'π π‘',
];
SENTENCES.flatMap(x => x.split(' '));
> (6)Β ["Hello", "world", "Goodbye", "world", "π", "π‘"]
// Something perhaps more exciting, getting all the class names.
Array.from(
document.querySelectorAll('*')
).flatMap(
el=>Array.from(el.classList)
);
> (512)Β ["post-template", "site-wrapper", "outer"...
Object.fromEntries
Transforms an array of key-value pairs into an object.
const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
Object.fromEntries(entries);
> { foo: "bar", baz: 42 }
String.prototype.matchAll
The matchAll()
method words like RegExp.prototype.exec
, but returns results as an iterable list.
const str = 'hello world and goodbye world.';
[...str.matchAll(/[a-z]*o[a-z]*/g)]
>
["hello", index: 0],
["world", index: 6],
["goodbye", index: 16],
["world", index: 24],
String.prototype.trimStart/trimEnd
A fairly basic methodβ not sure we'll be using this anytime soon. We'll stick with trim()
.
' hello world'.trimStart();
> 'hello world'
'hello world '.trimEnd();
> 'hello world'
New Syntax:
Optional Catch Parameter Binding
Now in ES10, developers don't need to use try/catch blocks with an error parameter inside the catch block.
try {;}
catch (err) {;}
try {;}
catch {;} // Notice we don't pass in an error variable?
Numeric Separator:
We've all wanted commas in our integers. I guess we get the second best thing now, underscores.
As a camelCase developer, I'll personally pass until the Unicode consortium adds uppercase numbers </sarcasm>
.
const num = 123_456_789.01;
> num = 123456789.01 // 123,456,789.01
const num2 = 654__321;
> SyntaxError: Only one underscore is allowed as numeric separator
const num3 = 1_2_3_4_5;
> num3 = 12345; // 12,345