DEV Community

Cover image for 5 most important features you should know about Javascript ES2022
Shivam Singh
Shivam Singh

Posted on

5 most important features you should know about Javascript ES2022

A new JavaScript standard known ECMAScript 2022 was introduced in June 2022.
It's crucial for developers to keep up with a language's new specifications, and the numerous modifications shouldn't make you feel like you've fallen behind.

1. Top Level Await Operator

Did you realise that code outside of a function couldn't utilise await directly? If you use await outside of your asynchronous function, you will get an error in the prior version. In ES2022, the await operator can be declared even outside of an asynchronous method.

What makes it useful?
It enables dynamic module loading.

const methodName = await fetch('https://abc.com/what-is-method-name')
const method = await import('/methods/${methodName }.js')
Enter fullscreen mode Exit fullscreen mode

2. Method .at() in arrays

In JavaScript, you can use the array[1] function to access an array's value at index 1, but you cannot use the array[-1] function to count backward from the array's end. The rationale is that objects can also utilise the brackets syntax; in this case, object[-1] simply refers to the object's property '-1'.

We now have a simple way to retrieve any index, positive or negative, of arrays and strings thanks to the.at() method.

Instead of writing:

const array = [5,6,7,8,9];
array[array.length - 1];  // 9
array[2];  // 7

const string = "abcd";
string[string.length - 1];  // d
string[2];  // c
Enter fullscreen mode Exit fullscreen mode

We can write

const array = [5,6,7,8,9];
array.at(-1);  // 9
array.at(2);  //  7

const string = "abcd";
string.at(-1);  // d
string.at(2);  // c
Enter fullscreen mode Exit fullscreen mode

Note that a negative value simply means: ‘Start counting backward from the end of the array’.

3. Error Cause

Historically, errors have been located and fixed during runtime utilising contextual data like error messages and error instance characteristics. Without a suitable exception design pattern, it may be challenging to pinpoint the root cause of an issue that occurs in a deeply nested function.

In ES2022, .cause property on the error object would allow us to identify which error led to the other problem by referencing the reason attribute on the error object. I think it's very self-explanatory. Here is an illustration of how this new capability is used:

try {
  // nested operation that throw an error
} catch (error) {
  throw new Error('Data processing failed', { cause: error })
}
Enter fullscreen mode Exit fullscreen mode

4. Class Private And Public Instance Fields

Before ES2022 we would define properties of a class in its constructor like this:

class Student {
  constructor() {
    // private field
    this._name = 'shivam';
    // public field
    this.age = 25;
  }

  setName(name){
        this._name = name;
  }
}

const student = new Student();

console.log(student.age);  
// 25 -  public fields are accessible outside of the class

console.log(student._name);
// ERROR - private fields are not accessible outside of the class

Enter fullscreen mode Exit fullscreen mode

Inside of the constructor, we defined two fields. As you can see one of them is marked with an _ in front of the name which is just a JavaScript naming convention to declare the field as private meaning that it can only be accessed from inside of a class method.

Declaring both public and private fields is now simpler in ES2022. Let's look at this revised illustration:

class Student {
  #name = 'shivam';   // private field
  age = 25;          // public field

  setName(name){
        this.#name = name;
  }
}

const student = new Student();

console.log(student.age);  
// 25 -  public fields are accessible outside of the class

console.log(student._name);
// ERROR - private fields are not accessible outside of the class

Enter fullscreen mode Exit fullscreen mode

The first thing to notice is that they do not have to be defined within the function Object() { [native code] }. Second, we can make private fields by appending # to their names.

The main difference from the previous example is that if we try to access or modify the field outside of the class, an actual error will be thrown.

5. Ergonomic Brand Checks For Private Fields

In earlier iterations, accessing a public field that hadn't been declared would result in an undefined error. Similar to this, you would receive an error message if you attempted to access a private field.

Your life is greatly simplified with ES2022, which comes to your aid. You can easily determine whether a field is present in a given class by using the "in" operator. The private classes will also have access to this tool.

Before

class ButtonToggle {

   // initialised as null
    #value = null;
    get #getValue(){
        if(!this.#value){
            throw new Error('no value');
        } 
        return this.#value
    }
    static isButtonToggle(obj){
        try {
            obj.#getValue;
            return true;
        } catch {
            // could be an error internal to the getter
            return false; 
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

After

class ButtonToggle {

   // initialised as null
    #value = null;
    get #getValue(){
        if(!this.#value){
            throw new Error('no value');
        } 
        return this.#value;
    }
    static isButtonToggle(obj){
       return #value in obj && #getValue in obj
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading

Top comments (1)

Collapse
 
hd profile image
hd-n

Thaanks for sharing Shivam, very usefull !