Betterprogramming. Pub/javascript -…

The new ES12 specification is finally here. Specification? JavaScript is not really an open source language; it is a language written to the ECMAScript standard specification. The TC39 Committee is responsible for discussing and approving new features. Who are they?

“ECMA International’s TC39 is a group of JavaScript developers, implementers, academics, and others who work with the community to maintain and evolve the definition of JavaScript.” – TC39. Es

Their release process consists of five phases. They’ve been doing annual releases since 2015. They usually occur around spring. The approval date for the next proposal is June.

There are two ways to reference any version of ECMAScript:

1) To its year: This new version will be ES2021

2) Number of iterations: This new release will be the 12th iteration, so it can be called ES12.

So what’s new with this version? What features can we get excited about?

replaceAll

A new function has been added to the String prototype. Prior to this addition, it was impossible to replace all instances of a substring without using a regular expression.

ES12 before:

// using Regex to replace
'1 2 1 2 1 2'.replace(new RegExp('2'.'g'), '0');
// another option
'1 2 1 2 1 2'.replace(/2/g.'0');

// we can create our own helper
function replaceAll(str, find, replace) {
 return str.replace(new RegExp(find, 'g'), replace);
}
Copy the code

Now:

'1 2 1 2 1 2'.replaceAll('2'.'0');
Copy the code

What happens if the search parameter is an empty string? It will return the replacement values between each UCS-2/UTF-16 code unit.

'x'.replace(' '.'_');
// '_x''xxx'.replace(/(? :)/g, '_');
// '_x_x_x_''xxx'.replaceAll('', '_');
// '_x_x_x_'
Copy the code

There are many questions on the subject on the Internet. Therefore, we can infer that this will be a useful feature. No knowledge of regular expressions is required to make it easy to access.

Promise.any

The new promise.any method is another useful tool. It takes an iterable promise as a parameter. When either of these are complete, it triggers the promise.any () parameter callback or returns the response. This depends on whether you use async/await.

If all promises fail, the method throws an AggregateError that combines all the different Promise errors. What doesn’t return an ordinary array? Mainly for compatibility. It will be an instance of Error, and you will get the stack trace. It would be nice to have this information if needed.

Let’s look at some examples.

  • Using traditional callback syntax:
Promise.any([
    Promise.reject('Error 1'),
    Promise.reject('Error 2'),
    Promise.resolve('success'),
]).then((result) = > {
    console.log('result:', result);
});
// result: success
Copy the code
  • Use async/await syntax:
(async() = > {const result = await Promise.any([
        Promise.reject('Error 1'),
        Promise.reject('Error 2'),
        Promise.resolve('success'),]);console.log(`result: ${result}`); }) ();// result: success
Copy the code

Let’s examine a sample error scenario:

(async() = > {try {
        const result = await Promise.any([
            Promise.reject('Error 1'),
            Promise.reject('Error 2'),
            Promise.reject('Error 3'),]);console.log(`result ${result}`);
    } catch (err) {
        console.log(`error: ${err.errors}`);
    }
})();
// error: Error 1,Error 2,Error 3
Copy the code

This is the fourth addition to the Promise prototype. For a quick review, for now, we can use the following:

  • [ES2020] Promise.allSettled: This method returns a promise that resolves when all the given promises have either been fulfilled or rejected. The returned object describes each individual promise result.

  • [ES2015] Promise.all: This method returns a promise that is fulfilled only if all the target promises were fulfilled.

  • [ES2015] Promise.race: This method will return a promise that will be fulfilled as soon as one of the promises is either rejected or fulfilled.

WeakRefs

JavaScript has an automatic garbage collection process. It can only collect objects that cannot be accessed. Every time you assign a value to an object, you’re creating one that protects it from garbage collection

// x is a strong reference to the object\
const x = { foo: 'bar' };
Copy the code

WeakRef serves an entirely different use case: holding a reference to an object that does not protect it from garbage collection. Because garbage collection is nondeterministic, there is no real guarantee that objects will be removed when, or even if, they will be. WeakRef takes advantage of this by giving you access to the object until it is collected.

WeakRef can only take objects as arguments.

function Foo() {}// strong reference to a Foo instance
const x = new Foo();// weak reference to the Foo's instance
const xWeak = new WeakRef(x);
Copy the code

To get this value back, use deref(), remembering that this method returns a strong reference to the object.

function Foo() {}

// strong reference to a Foo instance
const x = new Foo();

// weak reference to the Foo's instance
const xWeak = new WeakRef(x);

// strong reference to the Foo's instance
const xFromWeak = xWeak.deref();
Copy the code

Why is this useful? It allows you to improve the performance of your application based on the user’s device. We can cache large objects with WeakRef, meaning that machines with more memory can see an improvement in application performance. Those with limited memory can still work without consuming user memory.

Finalizers

Finalizers are another ES12 feature in memory areas. The purpose of this feature is to let you know when an object is garbage collected. It is implemented through JavaScript callbacks.

However, there are a few things to keep in mind:

  • There is no guarantee that the callback will be executed.

  • The target object has been cleaned and will not be accessible.

  • It is uncertain how long the callback will take. It can be a minute or an hour.

// object creation
let x = new Array(1000).fill(true);

// constructing the finalizer method
const cleanup = new FinalizationRegistry(key= > {
  // cleanup code should go here
});

// hooking the x variable to the finalizer
cleanup.register(x, 'fsdfs');

// object 'x' is now unreachable, finalizer callback might happen after
// object has been garbage collected
x = null;
Copy the code

This feature gives you the opportunity to do further cleaning to help optimize your application.

Note: This is not where you want to run critical code. This is a place designed to help further reduce the footprint of our in-memory Web applications.

Logical Assignment Operators

Finally, these new ES12 specifications come with long-awaited operators. New operator will logic assignment operator is combined with logic operation, &&, | |, and????

Operator &&=

Let’s compare its equivalent in ES11 to the new specification.

Before:

x && (x = y)
Copy the code

After:

x &&= y;
Copy the code

Example:

let x = 5;
const y = 10;
x &&= y;

console.log(x);
// result is 10
Copy the code

Operator ||=

Let’s compare its equivalent in ES11 to the new specification.

Before:

x || (x = y)
Copy the code

After:

x ||= y;
Copy the code

Example:

let x = 5;
const y = 10;
x ||= y;

console.log(x);
// result is 5
Copy the code

Operator ?? =

?? Is the null merge operator of JavaScript. Let’s review what it does, because it’s not very common.

Null merge operator (??) Is a logical operator that returns its right-hand operand if its left-hand operand is empty or undefined, otherwise returns its left-hand operand. – MDN network documents

Before:

x ?? (x = y);
Copy the code

After:

x ?? = y;Copy the code

Example:

let x;
const y = 10; x ?? = y;console.log(x);
// result is 10
Copy the code

Numeric Separators

This addition may not be as fancy, but it does help improve the readability of the code. Currently, when storing a long number in a var/let/const variable, it may not be readable.

Let’s look at an example. Let’s create a constant of a million. Obviously, long numbers are hard to read.

const oneMillion = 1000000;
Copy the code

With the new ES12 syntax, you can create separations between numbers using the _ character.

const oneMillion = 1 _000_000;
Copy the code

It can be used with binary and hexadecimal text:

const max8bits = 0b1111_1111;const message = 0xA0_B0_C0;
Copy the code

It’s definitely something I use a lot.