Photo by Andrew Neel on Unsplash
JavaScript 2021 - New Features - Part 1
ECMAScript 2021(ES12) : New Capabilities
The String replaceAll() function
The replaceAll() function is available on a string object. The replaceAll() function replaces occurances of a given string in the given string object and returns a new string object.
// String.replaceAll()
let str = "Namaste Java";
let str2 = str.replaceAll("Java", "Javascript");
console.log(str2); // Namaste Javascript
console.log(str); // unchanged - Namaste Javascript
str = "Namaste Namaste Namaste";
console.log(str.replaceAll("Namaste", "Vanakkam"));
// Output: Vanakkam Vanakkam Vanakkam
Numeric Separator
A numeric value can be segregated using underscore to enhance readability e.g representing financial data.
// Numeric separator
let num= 1_00_000_00;
console.log(num);
Logical Assignment Operators
The logical assignment operators can shorthand the amount of code to be written i.e the amount of code written is reduced. There are 3 logical assignment operator
and - &&
or - ||
// logical assignment operators
let a=true;
a &&= false;
console.log(a); // false
a=true;
a ||=false;
console.log(a); // true
In the above code all logical assignment operators are used.The behaviour is as follows
The and assignment operator(&&=) : When both the operands are true the operand1 is assigned the value true
op1 &&= op2
The or assignment operator(||=) : When either of the operands are true the operand1 is assigned the value true.
op1 ||=op2
Nullish assignment operator
It is a shorthand for the nullish operator. It helps in reducing the amount of code to be written
// Nullish assignment operator
let x;
let y = 10;
x ??= y;
console.log("x",x); // Output: 10
In the above code the variable x is assigned the value 10 because x is undefined.
Complete Code Listing
// String.replaceAll()
let str = "Namaste Java";
let str2 = str.replaceAll("Java", "Javascript");
console.log(str2); // Namaste Javascript
console.log(str); // unchanged - Namaste Java
str = "Namaste Namaste Namaste";
console.log(str.replaceAll("Namaste", "Vanakkam"));
// Output: Vanakkam Vanakkam Vanakkam
// Numeric separator
let num= 1_00_000_00;
console.log(num);
// logical assignment operators
let a=true;
a &&= false;
console.log(a); // false
a=true;
a ||=false;
console.log(a); // true
// Nullish assignment operator
let x;
let y = 10;
x ??= y;
console.log("x",x); // Output: 10