You know 0…? What’s 1?

Hi, I’m LBJ and today we’re talking about some new features worth mastering in 2022!

Now front-end development is fast, various technologies and frameworks emerge in an endless stream, a hundred flowers bloom, many people are unable to learn! The fact that JavaScript is the primary language for the front end is that while it is evolving fast, with new features coming out every year, it is up to JavaScript developers to evolve faster, as many relatively new features have already achieved high adoption rates

Here’s a look at the new features with high adoption rates, and 10 JS tips you should know about 2022

The body of the

1. Use??Instead of||Is used to determine that the value on the left of the operator isnullorundefined, the value on the right is returned

?? The operator is introduced in ES2020, also known as the Nullish coalescing Operator.

Its behavior similar | |, but more severe

| | operators are on the left is an empty string, or false, or 0 falsy value, will return the value of the back. And???? The right-hand value is returned only if the left-hand value of the operator is null or undefined. Therefore 0 | | 1 result is 1, 0?? 1 is equal to 0

For example,

const response = {
  settings: {
    nullValue: null.height: 400.animationDuration: 0.headerText: ' '.showSplashScreen: false}};const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world! '; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false
Copy the code

Browser Support

2. Use? .To simplify the&&And ternary operators

? . Also introduced in ES2020, it is called the optional chaining operator.

? Check whether the object on the left is null or undefined. If it is, it does not proceed further and returns undefined. If not, it returns the value on the right

For example,

var street = user.address && user.address.street;

var fooInput = myForm.querySelector('input[name=foo]')
var fooValue = fooInput ? fooInput.value : undefined

/ / to simplify
varstreet = user.address? .streetvar fooValue = myForm.querySelector('input[name=foo]')? .valueCopy the code

Note: Common writing

  • obj? .propObject properties
  • obj? .[expr]Object properties
  • func? . (... args)A call to a function or object method

Browser Support

3. Load on demand using dynamic import import() (optimizing static import)

We can use import statements to initialize load dependencies

import defaultExport from "module-name";
import * as name from "module-name";
/ /...
Copy the code

But statically imported import statements rely on the script tag of type=”module”, and sometimes we want to load modules on demand based on conditions, such as the following scenario:

  • When a statically imported module obviously slows down the loading speed of the code and is less likely to be used, it may not be needed immediately
  • When statically imported modules clearly take up a lot of system memory and are less likely to be used
  • When imported modules do not exist at load time, they need to be retrieved asynchronously
  • When an imported module has side effects, these side effects are only needed if certain conditions are triggered

At this point we can use dynamic import(), which, like functions, can be used anywhere and returns a promise

Basically, the following two forms are used

/ / form 1
import('/modules/my-module.js')
  .then((module) = > {
    // Do something with the module.
  });
  
 2 / / form
let module = await import('/modules/my-module.js');
Copy the code

Browser Support

4. Simplify async functions with top-level await (top-level await

In fact, the above code is useful

let module = await import('/modules/my-module.js');
Copy the code

The top-level await allows the developer to use an await field outside of an async function

so

/ / before
(async function () {
  await Promise.resolve(console.log('🎉'));
  / / > 🎉}) ();/ / simplified
await Promise.resolve(console.log('🎉'));
Copy the code

Browser Support

5. Use String. Prototype. ReplaceAll () to simplify the replace all one-time replacement String

String. The prototype. The replaceAll () usage and String. The prototype. The replace ()

But replace replaces only the first occurrence of the substring, whereas replaceAll replaces all

For example, to replace all a with a:

/ / before
console.log('aaa'.replace(/a/g.'A')) //AAA

/ / simplified
console.log('aaa'.replaceAll('a'.'A')) //AAA
Copy the code

Browser Support

6. Use Proxy instead of Object.defineProperty

Why do you use Proxy instead of Object.defineProperty

  • A Proxy is a Proxy for an entire Object, while Object.defineProperty can only be a Proxy for a property
  • Object defineProperty adds attributes that Proxy can listen for but object.defineProperty cannot
  • Object. DefineProperty does not
  • If the internal properties of an Object need to be recursively Proxy, the Proxy can recurse only when called, whereas Object.definePropery needs to do all recursion at once, which is worse than Proxy performance

It is also very simple to use. Proxy is essentially a constructor that generates an object through new and takes two arguments:

  • targetRepresents the target object to intercept (proxy)
  • handlerIs used to customize interception behavior (13)

For example, the basic implementation of reactive:

function reactive(obj) {
    return new Proxy(obj, {
        get(target, key) {
            // You can do dependency collection
            track(target, key)
            return target[key]
        },
        set(target, key, val) {
            target[key] = val
            // Trigger dependencies
            trigger(target, key)
        }
    })
}
Copy the code

Browser Support

7. Any get a set quicklyPromiseThe first one in the examplefulfilledthepromise

Promise.any Accepts a set of Promise instances as parameters

  • Just one of thempromiseIf it succeeds, return the one that has succeededpromise
  • If none of this set of iterablespromiseSuccess, return a failurepromise 和 AggregateErrorType instance

Writing to recommend

try {
  const first = await Promise.any(promises);
  // Any of the promises was fulfilled.
} catch (error) {
  // All of the promises were rejected.
}
Copy the code

or

Promise.any(promises).then(
  (first) = > {
    // Any of the promises was fulfilled.
  },
  (error) = > {
    // All of the promises were rejected.});Copy the code

Browser Support

8. Use BigInt to support large integer computation problems

ES2020 introduces a new data type, BigInt, to represent integers with arbitrary digits

For example,

// A value greater than 53 binary bits (equivalent to 16 decimal bits) cannot maintain accuracy
Math.pow(2.53) = = =Math.pow(2.53) + 1 // true

// BigInt
BigInt(Math.pow(2.53= = =))BigInt(Math.pow(2.53)) + BigInt(1) // false
Copy the code

In addition to using BigInt to declare a large integer, you can also use the form of a number followed by n, as in

1234 // A common integer 1234N // BigIntCopy the code

You need to understand BigInt’s support for numeric operations to avoid stepping on pits

operation Whether to support
The unary (+) operator N
+,*,-,**,%The operator Y
\ Division operator Operations with decimals are rounded
>>>Unsigned right shift operator N
Other displacement operators Y
Mix with Number N (must be converted to the same type)
Math object methods N
Comparison of Number and BigInt Y (loose equal ==)
Boolean expression Type Number object
JSON is used in N

Browser Support

9. Simplify arr. Length with array.prototype.at ()

Array.prototype.at() takes a positive or negative integer as an argument to retrieve the member at the specified position

The argument positive denotes the sequential number and negative denotes the penultimate number, which is handy for finding the elements at the end of an array

For example,

var arr = [1.2.3.4.5]
// Get the last bit before
console.log(arr[arr.length-1]) / / 5
/ / simplified
console.log(arr.at(-1)) / / 5
Copy the code

10. Use hash prefixes#Make the class field private

Fields marked with hash # prefix in a class are private and cannot be inherited by subclass instances

For example,

class ClassWithPrivateField {
    #privateField;
    #privateMethod() {
        return 'hello world';
    }
    constructor() {
        this.#privateField = 42; }}const instance = new ClassWithPrivateField()
console.log(instance.privateField); //undefined
console.log(instance.privateMethod); //undefined
Copy the code

As you can see, both the property privateField and the method privateMethod are privatized and not available in the instance

conclusion

A lot of new features are being used by a lot of people, especially? And? . And dynamically importing import().

Ok, that’s all for this article. If you have any questions, please point out ~🤞