Error By Night ❤️️ Alimam Miya

Error By Night ❤️️ Alimam Miya

JavaScript 2021: New Features

JavaScript 2021: New Features

Today, we’ll discuss some of the new features of JavasScript that are very useful and can help us achieve more by writing less code.

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

JavaScript is an easy-to-learn programming language that makes it suitable for beginners. Over the years, it has evolved so much that it’s almost everywhere. We’ve seen it on the front-end (React, Angular, or Vue.js), back-end (Node.js), creating a desktop application with ElectronJS, etc.

JavaScript has given some new features in 2021, which helps the developers in many ways. Some of the new features of JavaScript in 2021 are:


1) New Logical Operators

JavaScript has added three new logical operators to the existing collection. These three operators are, I) &&= , II) ||= , & III) ??= . Let’s discuss these operators in detail:

a) &&= operator:

Before diving into the explanation, take a look at the example code given below:

let a = 1;
let b = 2;
a &&= b;
console.log(a) // output for variable 'a' would be 2.

The line a&&= b is similar to the code block given below:

if(a) {
  a = b;
}

This logical operator is saying that if the variable a has a truthy value (which it is since it holds a non-zero value), then variable a should be assigned the value of the variable b. That’s why when we do console.log(a) , the value of the variable a evaluates to 2 instead of 1.

b) ||= operator:

Consider the following code block given below:

let a = 1;
let b = 2;
a ||= b;
console.log(b); // output for variable 'a' would be 1.

This operator is the opposite of the &&= operator. In this, the variable a will be equal to the variable b only and only if the variable a has a falsy value. The code block above is equivalent to the code given below:

if (!a) {
  a = b;
}

c) ??= operator:

This operator checks whether a value is null or is undefined. Consider the following example:

let a;
let b = 2;
a ??= 1;
console.log(a) // output for variable 'a' would be 1.// this code block is similar to the code given above.
// if(a === null || a === undefined) {
//   a = 1
// }

In the example given, the value for the variable ‘a’ evaluates to undefined so, the if condition evaluates to true and ‘a’ is assigned the value of 1.

2) String ‘replaceAll’ method

We all have used the string replace method to replace a character or words in a string with the element we specified. But it came with one limitation, this method only replaced the first occurrence of the character or word that we wanted to replace and the rest of the occurrences in the string remained the same. To replace all the characters or words, we have to use regular expressions.

Example:

// without regex
let str = 'JS is everywhere. JS is amazing!';
console.log(str.replace('JS', 'JavaScript')); // the output would be 'JavaScript is everywhere. JS is amazing!'// with regex
let str = 'JS is everywhere. JS is amazing!';
console.log(str.replace(/JS/g, 'JavaScript')); // the output would be 'JavaScript is everywhere. JavaScript is amazing!'.

With the replaceAll method, the need for regular expression is eliminated. Consider the code below:

let str = 'JS is everywhere. JS is amazing!';
console.log(str.replaceAll('JS', 'JavaScript')); // the output would be 'JavaScript is everywhere. JavaScript is amazing!'.

The method replaceAll replaces all the occurrences of the character or the word specified, with the element we specified.

3) Using underscores as a separator for integers

Integers are one of the data types among strings, arrays, etc. Sometimes integers become so large that it becomes almost difficult to count the number of elements present or to figure out that the number is a million or a billion.

With the introduction of this feature, we can improve the readability of our integers. We can use underscores to separate the digits, without converting the data type to string. Example:

let number = 1_000_000_000; // one billion
console.log(number) // 1000000000 (the number would remain an integer)

4) ‘Promise.any()’

If you don’t know what promises JavaScript is, then you should first read here.

Promise.any() is a new feature that takes several iterable promises and returns the promise that is fulfilled first. An example will make that clear for you:

const p1 = new Promise(resolve => setTimeout(resolve, 500, 'First'));
const p2 = new Promise(resolve => setTimeout(resolve, 800, 'Second'));
const p3 = Promsie.reject(1);const promises = [p1, p2, p3];Promise.any(promises)
.then(result => {
   console.log(result);
}) // the result would be 'First' because that's the promise, that is fulfilled first.
.catch(e => {
    console.log(e);
}

In case none of the promises gets fulfilled, then we will get an AggregateError . To handle the AggregateError , we will define a catch statement after the then statement. If you don’t know what then & catch blocks are, you can read about them here.

5) WeakRef and Finalizers

WeakRef are short for ‘Weak References. WeakRef allows holding a weak reference to an object. The weak reference that is being held is called a ‘target’. A weak reference does not prevent the object from being reclaimed by the garbage collector.

Garbage collection is a method of collecting the variables that are no longer needed, therefore freeing up the computer’s memory. To learn more about garbage collection, click the link here.

NOTE: WeakRef SHOULD ONLY BE USED AFTER GIVING A PROPER THOUGHT AND SHOULD BE AVOIDED WHENEVER POSSIBLE.

Let’s understand the following by an example:

const weakRefFunc = () => {
    const obj = new WeakRef({
       name: 'JavaScript'
    });
    console.log(obj.deref().name);
}
const test = () => {
    new Promise(resolve => {
     setTimeout(() => {
       weakRefFunc();
        resolve();
      }, 3000)
    })
    new Promise(resolve => {
     setTimeout(() => {
       weakRefFunc();
        resolve();
      }, 5000)
    })
}
test();

The deref method returns the target that is being held, if the target is garbage collected, then undefined is returned.

In this example, the variable obj is the weak reference that is being held.

The first time when the weakrefFunc is called inside the test function, it’s guaranteed that ‘JavaScript’ would be printed, but for the second time when it’s called, there is no guarantee that ‘JavaScript’would be printed since the variable obj could be garbage-collected due to it being held as a weak reference.

Finalizers

A Finalizer is mostly used with WeakRef but it can also be used individually. A finalizer tells when an object is garbage collected. Let’s understand this through an example:

→ First, we are going to create a finalizer using the FinalizationRegistry method.

const registerFinalizer = new FinalizationRegistry(data => console.log(data));const obj = {'name': 'JavaScript'};
registerFinalizer.register(obj, 'obj is collected now!')

Now, the variable registerFinalizer is an object which contains the register method which we are going to use.

registerFinalizer.register takes 2 arguments. First, the object that is to be watched for garbage collection, and second is the message that we want to display to the console when the object is garbage collected.

Now, when the variable obj will be collected by garbage collectors, a message saying ‘obj is collected now!’ will be printed out to the console.

Conclusion

JavaScript overall is an amazing language to learn, one of the main reasons is that it’s present everywhere. I find these new features discussed above pretty useful. JavaScript 2021 features are pretty amazing and I expect the same to happen next year.

Hope you have learned something new. If you enjoyed this post, recently I wrote a post on how to use Node.js with Google sheets. You can see that post here. Thank you all for taking out the time to read this.

Originally posted on - avascript.plainenglish.io

Interested in reading more such articles from Alimam Miya?

Support the author by donating an amount of your choice.

 
Share this