JavaScript 2021: New Features

The latest

  • Operators
  • WeakRef
  • Finalizers

JavaScript is an easy-to-learn programming language which 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) ??= . 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.

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!'.

about.jpg

Read the full source article here...
Blog

RayAhmed.ca © 2021