|Written by Ian Elliot|
|Wednesday, 08 April 2020|
The eleventh version of ECMA Script has just been finalized and we can look forward to some fun things as the year progresses. So what's new?
For me, given my particular interest in async coding, the addition of an allSettled method to the Promise is top of my list. We have had race and all for some time now, but these wait for the first Promise to resolve or all of them to resolve. The new method allSettled waits for all of the Promises to complete, even if they rejected. This isn't a difficult method to implement from scratch, but having it will simplify code.
Given I'm also keen on fluent method calls, or chaining, my second pick has to be optional chaining and the nullish coalescing operator- even if they do introduce a bit of black magic symbolism.
The big problem with chaining is what happens when one of the method calls goes wrong. In particular, what happens when a object isn't defined. For example:
will check to see if myObject.myMethod1 exists and returns undefined if it doesn't. Without the optional chaining operator the result would be a runtime error. You can use optional chaining multiple times in a fluent call and you can use it with properties, functions, array access and expressions. The operator .? may look weird, but the if statements it replaces are far worse.
The nullish coalescing operator ?? is also a little weird, but it is very useful. It is a logical operator that returns its right-hand operand as long as the left-hand isn't nullish i.e. null or undefined. Its like the OR || operator but it doesn't respond to a falsy value on the left. Typically you can use ?? to assign a default value more safely than with the OR:
let myVariable=myValue ?? 42;
This sets myVariable to 42 if myValue is null or undefined, whereas:
let myVariable=myValue || 42;
sets it to 42 if myValue is falsy i.e. 0, "" etc.
This is a fix worth having.
Another function-oriented change is the introduction of the String method matchAll which produces an iterator for all matches to a regular expression. For example, you can write:
and the loop will repeat for all substrings that regexp matches. You can use the method call anywhere an iterator is expected and this gives it more flexibility than you might expect. For example:
creates an array from the matches.
Other useful extras are BigInt for unlimited integer support, dynamic import and a new globalThis keyword that always gives you the global object, no matter what the context.
Of course, most of these features are already supported in the current browsers, but now they are official.
Summer SALE Kindle 9.99 Paperback $10 off!!
or email your comment to: firstname.lastname@example.org
|Last Updated ( Friday, 10 April 2020 )|