7 New features In JavaScript You Should Try In 2022🔥!
Published: 2022-01-09 18:06:45

JavaScript has been getting continous updates since 2015, every update more awesome than the other. Everytime these updates are out, programmers from all around the world gets eager to test it out.

So, to all the impatient programmers out there, Today, I have brought bunch of cool feature proposals for you to check out this year. These made their way to the Stage 4 and are lined up to be part of the `Standard EcmaScript` probably till June 2022.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1641739259051/UtQdnm8f_.png)

**SOURCE:** https://medium.com/geekculture/typescript-vs-javascript-e5af7ab5a331

## 1️⃣ Private Methods and Accessor for Classes 

To full leverage OOP's (Object Oriented Programming) Data Hiding Concept, This proposal provides any element inside a class to be private, let it be **fields**, **methods** or **accessors(getter/setter)**. Thus, we can easily focus on **data security**🔒.

```js
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: can't be accessed or modified from outside the class
console.log(button.#value); 
button.#value = false;
```
> We have used `#` before the field to signify it as a private field.


## 2️⃣ Top Level `await`

Till now, we have been using `await` operator only with a `async` (asynchronous) function. What if I tell you that you can use `await` **without** the `async` function with this feature. 

Yes, We can use it! **at the top level of a module without declaration of a `async`.**

*Isn't it cool?*

```js
const params = new URLSearchParams(location.search);
const language = params.get('lang');
const messages = await import(`./messages-${language}.mjs`); // (A)

console.log(messages.welcome);
```
> The dynamic import in line (A) is almost as convenient as using a normal, static import since we’re using top-level await.

Now the question arises that

### Why would we need a `await` at the **top level of a module**🤔?

* ✅ Some modules contains asynchronously loaded data, thus It ensures that modules don’t access asynchronous imports before they are fully initialized.
* ✅ In addition, Asynchronous modules are handled transparently by the system: Importers do not need to know if they are asynchronous or not.

However, top-level await slows down initialization of importing modules. 


## 3️⃣ Private Slot Checks

**Did you know?** Private fields have a built-in `"brand check"`, which means that if you try to access **a private field within an object** that doesn't have it installed, the process **throws an exception**.

So, to check if object has a private slot or not, `in` operator is used. 

```js
class Color {
  #name;
  constructor(name) {
    this.#name = name;
  }
  static check(obj) {
    return #name in obj; // (A)
  }
}
```
 **In the code above, we are checking if object `obj` has private slot `#name` or not.*

> We can use `in` operator to check **private fields and methods** as well as **static fields and methods**.


## 4️⃣ `new Error()` method

Errors are a great way to diagnose runtime irregularies. This proposals brings forward concept of **chaining errors with causes** to  additionally help in diagnosing these runtime irregularities.

So, now we can specify the exact error that caused the current error by using `new Error` and its subclasses.

```js
function readFiles(filePaths) {
  return filePaths.map(
    (filePath) => {
      try {
        // ···
      } catch (error) {
        throw new Error(
          `While processing ${filePath}`,
          {cause: error}
        );
      }
    });
}
```
> The property `cause` in used to get additional information on the error.

## 5️⃣ `.at()` function 

**This one's a little interesting!!** .Till now, we have been using square brackets `[]` for indexing purposes in JavaScript.

But,  What if we use negative indices instead in this technique?

```js
arr = [1,2,3,4,5]
arr[3] // 4

arr[-1] // (A)
// the code breaks here!
```
> *The code just breaks at line (A)

In contrast, Array method .at() does the same task but supports both positive and negative indices. Thus, we can access the same list in reverse order with the use of negative indexing.

```js
arr.at(-1) // 5
arr.at(-3) // 3
```


 ## 6️⃣ RegExp Match Indices

This one is a very useful addition the *match object*. The *match indices* are a feature of *match objects*. If we enable it via the regular expression flag `/d`, they provide the **start and end indexes** of where each group was captured.

```js
const fruits = 'Fruits: mango, mangosteen, orange'
const regex = /(mango)/g;

// matchAll
const matches = [...fruits.matchAll(regex)];
matches[0];
```
```
 [
   "mango",
   "mango",
   index: 8,
   input: 'Fruits: mango, mangosteen, orange',
   groups: undefined
 ]
```

Look closely what we are going to do next. the `/mango/g` will now be converted to `/mango/gd`.

```js
// /gd instead of the previous /g
const regex = /(mango)/gd;
const matches = [...fruits.matchAll(regex)];
matches[0];
```
```
 [
 "mango",
 "mango",
 groups: undefined,
 index: 8,
 indices:[]
  [8, 13],
  [8, 13]
 ]
```
> Just with the addition of a `/d` in the Regex, our *match object* will provide us with a additional property `indices`.



## 7️⃣ Object.hasOwn Function

This proposal is meant to redefine the `Object.hasOwnProperty`, simplifying the unnecessary hassels faced by the programmer.

Its working is Simple! If the specified object has the specified property as its own property, the Object.hasOwn() static method returns true. If the specified property is inherited, or does not exist, the method returns false.

```js
let hasOwnProperty = Object.prototype.hasOwnProperty

if (hasOwnProperty.call(object, "foo")) {
  console.log("has property foo")
}
```
This was the code that we were writing till now!🔝 

```js
if (Object.hasOwn(object, "foo")) {
  console.log("has property foo")
}
```
Look, How much it simplified the code🔝 !! 

> Thus, `Object.hasOwn()` will replace `Object.hasOwnProperty` is year💡! 




## What's Next ⁉️

There might be some more feature that can be added to `EcmaScript 2022`. So, Stay tuned and follow me on:

**Twitter:** https://twitter.com/tanmay_vaish

**LinkedIn:** https://www.linkedin.com/in/tanmay-vaish/

**GitHub:** https://github.com/tanmayVaish

**Hashnode:** https://hashnode.com/@tanmayVaish


## Acknowledgements

* [TC39 Page for Finished Proposals](https://github.com/tc39/proposals/blob/main/finished-proposals.md)

* [exploringjs.com](https://exploringjs.com/impatient-js/ch_new-javascript-features.html#new-in-es2022)

* [InspiredWebDev](https://inspiredwebdev.com/everything-new-in-es2022/#class-public-instance-fields--private-instance-fields) by [Alberto Montalesi](https://twitter.com/montalesi). 

* [Codedamn](https://youtu.be/TiVPWhEJGF8) by [Mehul Mohan](https://twitter.com/mehulmpt)

* [v8.dev](https://v8.dev/features/top-level-await)

* [Top-level 'await' is a footgun](https://gist.github.com/Rich-Harris/0b6f317657f5167663b493c722647221) by [Rich Harris](https://twitter.com/Rich_Harris)