April 13, 2020

Es2020 New features part2

This is the second and final piece of the series dedicated to Es2020. Here you can find the first part where we talked about Dynamic import, BigInt and Module namespace exports. Let’s go ahead.

String.prototype.matchAll

Regular expressions are the weak point of many developers (including me!) but they are useful and powerful so let’s not back down. Let’s take a string:

const string = 'A gun is a tool, Marian; no better or no worse than any other tool: an ax, a shovel or anything. A gun is as good or as bad as the man using it. Remember that.' 

Alan Ladd in “Shane” 1953

Let’s pretend we want to find all the occurrences of the word gun and let’s write down our own regular expression:

const regex = /gun/g;

Using the old match function we will get an array of two elements. The two occurrences of the word gun:

console.log(string.match(regex)) // ['gun', 'gun'] 

What happens instead using matchAll ? We get an iterable object that contains all the information related to the two occurrences of the word we are looking for.

for (const match of string.matchAll(regex)) {
    console.log(match) 
}

// { 0: "gun" index: 2 input: "A gun is a tool, Marian; no better ..." }
// { 0: "gun" index: 99 input: "A gun is a tool, Marian; no better ..." }

Note that in order to use match all we are forced to perform a global match, so to use the /g modifier. Otherwise we will receive the following error:

Uncaught TypeError: undefineds called with a non-global RegExp argument

globalThis

It’s a global variable valid in any environment. You can use it in case you are not sure you have the Window object available or in general when you don’t know in which environment your code will run.

Optional chaining

This is really really useful. Long chains of property accesses in javascript had a huge risk of errors because each piece of the chain could have been undefined and make everything go wrong.

const nestedProperty = my.object.is.very.very.long.and.if.this.word.is.undefined.my.code.explodes


VM2199:1 Uncaught TypeError: Cannot read property 'my' of undefined
    at <anonymous>:1:26

To avoid errors, we are forced to write tons of if/else that make our code difficult to read and a little ugly. With the optional chaining we can solve this issue in a short and elegant way:

const nestedProperty = my?.object?.is?.very ..

Nullish coalescing

The nullish coalescing operator is a logical operator which returns the first value if it’s not null or undefined. Otherwise it returns the second value. Simple enough, let’s try:

console.log('Fill your hands' ?? 'you son of a bitch!')
// Fill your hands

console.log(null ?? 'you son of a bitch!')
// you son of a bitch!

True Grit 1969

No copyright / do whatever the hell you want with these contents
Built with Hugo and Kiss theme. Hosted on Netlify. Icons made by Ddara