New JS Features of ES2021 — Part 1
Hello dev. Let’s have a look at the new and exciting features of ES2021.
1. Numeric separators
This new feature lets us to have underscores ( _ ) between the digits in a number. For example,
const numOne = 10_000_333;
const numTwo = 2_555_100;
The above declared numbers can be added, subtracted or manipulated as we need. Here the advantage of the separator is its readability. It is easier to read 10_000_333 than 10000333. Isn’t it?
2. String.prototype.replaceAll
The replaceAll feature lets us to replace all occurrences of a sub-string in a string. For example,
const someText = “Hello*world*cheers!”;
const spacedText = someText.replaceAll(“*”, “ “);
console.log(spacedText);
In above code we are replacing all instances of * with a space.
The following features are more about shorthand notations and it is really cool.
3. AND & Equals (&&=)
Simply put, &&= can check if the variable is defined or not, if defined with a truthy value, then a preferred value is assigned to the variable.
Get Alagarasan M’s stories in your inbox
Join Medium for free to get updates from this writer.
Old way:
let randomValue = 1;
if(randomValue) {
randomValue = 100;
}
New way:
let randomValue = 1;
randomValue &&= 100;
console.log(randomValue); //Output: 100
4. OR & Equals (||=)
Here the ||= can check if the given value is falsey one or not. If the value is falsey then it will be replaced with a preferred value.
Old way:
let randomText = undefined;
if(! randomText) {
randomText = “Hi ES2021.”;
}
New way:
let randomText = undefined;
randomText ||= “Hi ES2021.”;
console.log(randomText); //Output: Hi ES2021.
5. Nullish Coalescing & Equals (??=)
This shorthand notation ??= assigns the preferred value, when the given value is null or undefined.
let someValue = undefined;
someValue ??= 1000;
console.log(someValue); //Output: 1000
PS: The difference between OR & Equals and Nullish Coalescing & Equals is that the former feature replaces the value if the variable contains any kind of falsey values like 0, false, null etc., whereas the latter feature replaces the value only if the given variable contains null or undefined.
To be continued…
Thank you!






