DEV Community

Cover image for 7 New features In JavaScript You Should Try In 2022🔥!
Tanmay Vaish
Tanmay Vaish

Posted on • Originally published at tanmay-vaish.hashnode.dev

7 New features In JavaScript You Should Try In 2022🔥!

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

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🔒.

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;
Enter fullscreen mode Exit fullscreen mode

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?

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

console.log(messages.welcome);
Enter fullscreen mode Exit fullscreen mode

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.

class Color {
  #name;
  constructor(name) {
    this.#name = name;
  }
  static check(obj) {
    return #name in obj; // (A)
  }
}
Enter fullscreen mode Exit fullscreen mode

*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.

function readFiles(filePaths) {
  return filePaths.map(
    (filePath) => {
      try {
        // ···
      } catch (error) {
        throw new Error(
          `While processing ${filePath}`,
          {cause: error}
        );
      }
    });
}
Enter fullscreen mode Exit fullscreen mode

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?

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

arr[-1] // (A)
// the code breaks here!
Enter fullscreen mode Exit fullscreen mode

*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.

arr.at(-1) // 5
arr.at(-3) // 3
Enter fullscreen mode Exit fullscreen mode

## 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.

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

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

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

// /gd instead of the previous /g
const regex = /(mango)/gd;
const matches = [...fruits.matchAll(regex)];
matches[0];
Enter fullscreen mode Exit fullscreen mode
 [
 "mango",
 "mango",
 groups: undefined,
 index: 8,
 indices:[]
  [8, 13],
  [8, 13]
 ]
Enter fullscreen mode Exit fullscreen mode

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.

let hasOwnProperty = Object.prototype.hasOwnProperty

if (hasOwnProperty.call(object, "foo")) {
  console.log("has property foo")
}
Enter fullscreen mode Exit fullscreen mode

This was the code that we were writing till now!🔝

if (Object.hasOwn(object, "foo")) {
  console.log("has property foo")
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)