At the time of this writing, the new JavaScript proposal features mentioned in this article are in phase 4 and will almost certainly be included in ES2021. You can already start using it in the latest versions of browsers, Node.js and Babel.

Note: ECMAScript is the standard on which JavaScript is based and is governed by the TC39 committee. ECMAScript is always an unwanted name, which can make everything confusing for beginners. People talk a lot about JavaScript functionality, but refer to the ECMAScript specification.

Update feature

  • Numeric separator(_)
  • Distribution of logic(&& =.| | =.?? =)
  • Lack of reference(WeakRefandFinalizationRegistry)
  • Promise.any
  • String.prototype.replaceAll

1. Numeric delimiters

Large numeric text is difficult for the human eye to parse quickly, especially when there are many repeated numbers:

1000000000000   1019436871.42
Copy the code

To improve readability, the new JavaScript language feature enables underscores as separators in numeric text. Therefore, the above can now be rewritten as digits per thousand, for example:

1 _000_000_000_000 _019_436_871. 42Copy the code

Now, it’s easier to say that the first number is 1 trillion, and the second number is about 1 billion.

Numeric delimiters help to improve readability of various numeric literals:

// A decimal integer literal with its digits grouped per thousand: 1_000_000_000_000 // A decimal literal with its digits grouped per thousand: 1_000_6000. 220_720 // A binary INTEGER literal with its bits Grouped per octet: 0b01010110_00111000 // A binary integer literal with its bits grouped per nibble: 0b0101_0110_0011_1000 // A hexadecimal integer literal with its digits grouped by byte: 0x40_76_38_6A_73 // A BigInt literal with its digits grouped per thousand: 4_642_473_943_484_686_707nCopy the code

They even work with octal integer literals (although I can’t think of an example where a delimiter provides a value for such literals) :

// A numeric separator in an octal integer literal: 🤷♀️
0o123_456
Copy the code

Note that JavaScript also has the old-fashioned syntax of octal literals without an explicit 0O prefix. For example, 017 === 0O17. This syntax is not supported in strict mode or in modules, and should not be used in modern code. Therefore, these literals do not support numeric separators. Use 0O17 style text instead.

2. Promise combinators

Since the introduction of Promises in ES2015, JavaScript has fully supported two Promise combinators: static methods promise.all and promise.race.

Two new proposals are currently going through the standardized process: Promise.AllSettled and Promise.any. With these additions, JavaScript will have a total of four promise combinators, each supporting a different use case.

Here’s an overview of the four combinators:

2.1 Promise. AllSettled

Promise. AllSettled gives you a signal when all input promises are settled, which means they either fulfill or reject. This is useful if you don’t care about the state of the commitment and just want to know when the work is done, whether it succeeds or not.

For example, you can start a series of separate API calls and use promise.allSettled them to make sure they are all complete before performing other operations, such as removing the load spreader:

const promises = [
  fetch('/api-call-1'),
  fetch('/api-call-2'),
  fetch('/api-call-3')];// Imagine some of these requests fail, and some succeed.

await Promise.allSettled(promises);
// All API calls have finished (either failed or succeeded).
removeLoadingIndicator();
Copy the code

2.2 Promise. Any

The promise.any method is similar to promise.race — whenever a Promise in a given iteration succeeds, the value of the first Promise is taken as its return value, Unlike promise.race, however, it will wait until all promises have failed before returning the failed value:

const promises = [
  fetch('/endpoint-a').then(() = > 'a'),
  fetch('/endpoint-b').then(() = > 'b'),
  fetch('/endpoint-c').then(() = > 'c')];try {
  const first = await Promise.any(promises);
  // Any of the promises was fulfilled.
  console.log(first);
  / / - e.g. 'b'
} catch (error) {
  // All of the promises were rejected.
  console.assert(error instanceof AggregateError);
  // Log the rejection values:
  console.log(error.errors);
  / / - > [
  // 
      
       ,
      
  // 
      
       ,
      
  // 
      
  / /]
}
Copy the code

This code example checks which endpoint is the most responsive and then logs it. Only when all requests fail do we end up in the code catch block, where we handle the error.

Any rejection can represent more than one error at a time. To support this functionality at the language level, a new error type called AggregateError has been introduced. In addition to the basic usage in the example above, an AggregateError object can be constructed programmatically, just like any other error type:

const aggregateError = new AggregateError([errorA, errorB, errorC], 'Stuff went wrong! ');
Copy the code

3. Weak references and finalizers

This feature includes two high-level objects, WeakRef and FinalizationRegistry. Depending on usage, these interfaces can be used separately or together. Their proper use requires careful consideration and is best avoided if possible.

In general, in JavaScript, references to objects are strongly reserved, meaning that as long as a reference to an object is held, it is not garbage collected.

const ref = { x: 42.y: 51 };
// As long as we access the ref object (or any other reference to it), it will not be garbage collected
Copy the code

Currently in Javascript, WeakMap and WeakSet are the only ways to weakly reference an object: adding an object as a key to a WeakMap or A WeakSet does not prevent it from being garbage collected.

JavaScript’s WeakMap is not really a weak reference: in fact, it strongly references the contents of the key as long as it is still alive. WeakMap weakly references its contents only after the key is garbage collected.

WeakRef is a more advanced API that provides true weak references. A WeakRef instance has a method, deref, that returns the referenced original object or undefined object if the original object has been collected.

Object reference in JavaScript is a strong reference. WeakMap and WeakSet can provide some weak reference functions. If you want to achieve real weak reference in JavaScript, you can use WeakRef and Finalizer together to achieve it.

WeakRef is used to refer to objects that retain a target object without leaving garbage collection. WeakRefs can de-reference the target object to allow access if the target object is not collected through garbage collection.

// Create a WeakRef object referring to a given target object
const ref = new WeakRef(targetObject)

// Return the WeakRef instance's target object, or undefined if the target object has been garbage-collected
const obj = ref.deref()
Copy the code

The FinalizationRegistry object is used to request a callback when an object is garbage collected.

// Create a registry object that uses the given callback
const registry = new FinalizationRegistry([callback])

// Register an object with a registry instance so that if the object is garbage-collected, the registry's callback may get called
registry.register(target, heldValue, [unregisterToken])

// Unregister a target object from a registry instance
registry.unregister(unregisterToken)
Copy the code

More information: TC39 proposal, V8

4. String.prototype.replaceAll

Currently, you cannot replace all instances of a substring of a string without using a global regular expression. When used with String arguments, string.prototype. replace affects only the first occurrence.

String. The prototype. The replaceAll () will provide a simple way for developers to complete the common basic operation.

'aabbcc'.replaceAll('b', '.') // 'aa.. cc' 'aabbcc'.replaceAll(/b/g, '.') // 'aa.. cc'Copy the code

5. Logical assignment

Support with the new operation logic distribution && =, | | = and?? =. Unlike their mathematical and bitwise counterparts, logical assignments follow the short-circuiting behavior of their respective logical operations. They perform allocation only if the logical operation will evaluate the right side.

// falsy: false, 0, -0, 0n, "", null, undefined, and NaN
// truthy: all values are truthy unless defined as falsy
// nullish: null or undefined

a ||= b
// Logical OR assignment
// Equivalent to: a || (a = b);
// Only assigns if a is falsy

a &&= b
// Logical AND assignment
// Equivalent to: a && (a = b);
// Only assigns if a is truthya ?? = b// Logical nullish assignment
// Equivalent to: a ?? (a = b);
// Only assigns if a is nullish
Copy the code

5.1 Specific Examples

with&&The logical assignment operator of the operator

The value of the RHS variable is assigned to the LHS variable only if the LHS value is true.

// Logical Assignment Operator with && operator
let num1 = 5
let num2 = 10
num1 &&= num2
console.log(num1) / / 10
// Line 5 can also be written as following ways
// 1. num1 && (num1 = num2)
// 2. if (num1) num1 = num2
Copy the code

with||Operator of the logical assignment operator

The value of the RHS variable is assigned to the LHS variable only if the LHS value is false.

// Logical Assignment Operator with || operator
let num1
let num2 = 10
num1 ||= num2
console.log(num1) / / 10
// Line 5 can also be written as following ways
// 1. num1 || (num1 = num2)
// 2. if (! num1) num1 = num2
Copy the code

with??The logical assignment operator of the operator

ES2020 introduces the null-value merge operator, which can also be used in conjunction with the assignment operator. The value of the RHS variable is assigned to the LHS variable only when LHS is undefined or null.

// Logical Assignment Operator with ?? operator
let num1
let num2 = 10num1 ?? = num2console.log(num1) / / 10
num1 = falsenum1 ?? = num2console.log(num1) // false
// Line 5 can also be written as following ways
// num1 ?? (num1 = num2)
Copy the code

summary

As a developer, it’s important to keep up with the new features of the language.

Some of these new features, which will be released in 2021, are phase 4 proposals that will almost certainly be included, and are already implemented in the latest browsers and Babel.

Welcome to pay attention to the public number: “full stack cultivation”, reply to “e-book” that you can get 160 front-end elite books oh.

See article: JavaScript Features in 2021

Past pure text

  • Vue3 Family buckets + Element Plus + Vite + TypeScript + Eslint Project configuration best practices

  • 10 Advanced Tips for Improving Happiness in TypeScript

  • Amazing!!! Visual JS: dynamic graph demo – Event Loop

If you get something from this post, please give me a “like”. This will be my motivation to keep sharing. Thank you