You should try these 8 new JS functions

Posted by libertyct on Fri, 21 Jan 2022 01:30:08 +0100

Abstract: This paper mainly introduces several proposals that have entered stage 4, which are expected to be gradually incorporated into the standard in 2022.

This article is shared from Huawei cloud community< 8 new JavaScript features you should try in 2022 >, author: front end picker.

Since the joint release of JavaScript by Netscape and Sun on December 4, 1995, JavaScript has developed rapidly since its launch. ES6 was officially released in June 2015. Since then, JavaScript has officially entered a new stage, becoming an enterprise level large-scale development language and still developing at a high speed.

The following table corresponds to this version change:

This paper mainly introduces several proposals that have entered stage 4, which are expected to be gradually incorporated into the standard in 2022. (please note: inclusion criteria are not equivalent to browser support)

PS: the new syntax of popular science Javascript has gone through the following stage s from putting forward to incorporating the standard

stage-0: the new grammar is still an idea (it can only be proposed by TC39 members or TC39 contributors)

stage-1:: in the proposal stage, formal proposals can only be initiated by TC39 members. The problems to be solved by this proposal must be formally described in writing.

stage-2: draft. With the initial specification, the functional syntax and semantics must be formally described, including some experimental implementations.

stage-3: candidate. The proposal has been basically realized and needs to wait for experimental verification, user feedback and acceptance test.

stage-4: it has been completed and must pass the Test262 acceptance test. The next step is to incorporate it into the ECMA standard.

.at()

TC39 recommends adding in all basic indexable classes, such as arrays, strings, and arguments at() method.

for example

lat arr=[1,2,3,4,5]

Before, we wanted to get the second bit in the array

arr[1] //2

The last one, maybe

arr[4] // 5

But what if the arr length is dynamic? How do we get the last one out? The usual wording is:

arr[arr.length-1]

But there is The at() method is simple at() supports positive and negative indexes.

for example

arr.at(-1)  //5
arr.at(-2)  //4

Specific proposals: https://github.com/tc39/proposal-relative-indexing-method

Object.hasOwn(object, property)

Object.hasOwn(object, property) is mainly used to replace object prototype. hasOwnProperty().

At present, we want to judge whether an object has a specified object. The main writing method is as follows:

if (Object.prototype.hasOwnProperty.call(object, "fn")) {
  console.log('have')
}

And object How to write hasown:

if (Object.hasOwn(object, "fn")) {
  console.log("have")
}

Specific proposals: https://github.com/tc39/proposal-accessible-object-hasownproperty

At present, version 9.3 of V8 engine has been supported, so chrome should be supported soon.

Class and getter/setter

Class is the basis of all object-oriented languages. Although Javascript supports using class to define classes, it does not provide a scheme to define private properties / methods. This proposal proposes to use * * #* * to define private attributes / methods

class Person{
    name = 'Xiao Fang';
    #age = 16;
    consoleAge(){
       console.log(this.#age)
    }
}
const person = new Person();
console.log(person.name); //Xiao Fang
console.log(button.#value); // report errors
button.#value = false;// report errors

Specific proposals: https://github.com/tc39/proposal-private-methods

Check private properties and methods

Because the new standard will support private properties and methods, we will report an error when accessing non-existent private properties / methods. This situation is also considered in the new standard, and in is provided to check whether private properties and methods exist

class C {
  #brand;

  #method() {}

  get #getter() {}

  static isC(obj) {
    return #brand in obj && #method in obj && #getter in obj;
  }
}

Specific proposals: https://github.com/tc39/proposal-private-fields-in-in

Top level await

At present, we must use await in functions that declare async. This proposal mainly supports the use of await without async

For example, the following usage scenarios:

Dynamic introduction of dependency

const strings = await import(`/i18n/${navigator.language}`);

This allows the module to use runtime values to determine dependencies. This is very useful for development / production splitting, internationalization, environment splitting, etc.

Resource initialization

const connection = await dbConnector();

This allows the module to represent resources and generate errors if the module can never be used.

Load dependency

let jQuery;
try {
  jQuery = await import('https://cdn-a.com/jQuery');
} catch {
  jQuery = await import('https://cdn-b.com/jQuery');
}

Specific proposals: https://github.com/tc39/proposal-top-level-await

Regular matching index

The proposal provides a new / d to obtain the start position and end position information of each match.

const str = 'The question is TO BE, or not to be, that is to be.';
const regex = /to be/gd;

const matches = [...str.matchAll(regex)];
matches[0];

Specific proposals: https://github.com/tc39/proposal-regexp-match-indices

new Error() the specific reason for throwing the exception

new Error(), maybe your first reaction is that this is not an existing grammar. Yes, that's right! Just a new proposal: associate the error with the cause, add an additional option parameter cause to the error () constructor with the attribute, and its value will be assigned to the error instance as the attribute.

async function doJob() {
  const rawResource = await fetch('//domain/resource-a')
    .catch(err => {
      throw new Error('Download raw resource failed', { cause: err });
    });
  const jobResult = doComputationalHeavyJob(rawResource);
  await fetch('//domain/upload', { method: 'POST', body: jobResult })
    .catch(err => {
      throw new Error('Upload job result failed', { cause: err });
    });
}

try {
  await doJob();
} catch (e) {
  console.log(e);
  console.log('Caused by', e.cause);
}
// Error: Upload job result failed
// Caused by TypeError: Failed to fetch

Specific proposals: https://github.com/tc39/proposal-error-cause

Class static initialization block

Honda provides a mechanism for static fields and static private fields to initialize each field on the static side of the class during ClassDefinitionEvaluation - static blocks For example, official examples:

Before static blocks, if we want to initialize static variables (non direct assignment, possibly expression assignment), it may be implemented externally:

// without static blocks:
class C {
  static x = ...;
  static y;
  static z;
}

try {
  const obj = doSomethingWith(C.x);
  C.y = obj.y
  C.z = obj.z;
}
catch {
  C.y = ...;
  C.z = ...;
}

With static blocks, we can directly initialize variables in static blocks:

class C {
  static x = ...;
  static y;
  static z;
  static {
    try {
      const obj = doSomethingWith(this.x);
      this.y = obj.y;
      this.z = obj.z;
    }
    catch {
      this.y = ...;
      this.z = ...;
    }
  }
}

 

Click focus to learn about Huawei cloud's new technologies for the first time~

Topics: github