What's new in ES2022

What’s new in ES2022

Please note that most of the examples in this lesson won’t run on the Educative platform, to play around with them you can use the Chrome developer tools.

Let’s get started with the first of the new ES2022 features:

Class Fields

Class public Instance Fields & private Instance Fields

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

Press + to interact
class ButtonToggle extends HTMLElement {
constructor(){
super();
// public field
this.color = 'green'
// private field
this._value = true;
}
toggle(){
this.value = !this.value
}
}
const button = new ButtonToggle();
console.log(button.color);
// green - public fields are accessible from outside classes
button._value = false;
console.log(button._value);
// false - no error thrown, we can access it from outside the class

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. Of course, that’s just a naming convention and not something that the language itself enforces and that’s why when we tried to access it, it didn’t raise any error.

In ES2022 we have an easier way to declare both public and private fields. Let’s have a look at this updated example:

Press + to interact
class ButtonToggle extends HTMLElement {
color = 'green';
#value = true;
toggle(){
this.#value = !this.#value;
}
}
const button = new ButtonToggle();
console.log(button.color);
// green - public fields are accessible from outside classes
// SyntaxError - cannot be accessed or modified from outside the class
console.log(button.#value);
button.#value = false;

The first thing to notice is that don’t have to define them inside of the constructor. Secondly, we can also define private fields by pre-pending # to their names.

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

 

Private methods and getter/setters for JavaScript classes

Similar to how we ...

Access this course and 1400+ top-rated courses and projects.