What's new in ES2022
We'll cover the following...
- What’s new in ES2022
- Class Fields
- Class public Instance Fields & private Instance Fields
- Private methods and getter/setters for JavaScript classes
- Static class fields and private static methods
- Ergonomic brand checks for private Fields
- Class Static Block
- RegExp Match Indices
- Top-level await
- .at()
- Accessible Object.prototype.hasOwnProperty
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:
class ButtonToggle extends HTMLElement {constructor(){super();// public fieldthis.color = 'green'// private fieldthis._value = true;}toggle(){this.value = !this.value}}const button = new ButtonToggle();console.log(button.color);// green - public fields are accessible from outside classesbutton._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:
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 classconsole.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 ...