The Latest Features in ECMAScript 2021
Have you heard the news? ECMAScript 2021 has arrived with exciting new features and updates to make your JavaScript programming experience smoother and more efficient than ever before!
As the formal name for JavaScript, ECMAScript is the standard that defines the syntax, semantics, and features of this widely used programming language. Every year, ECMAScript releases a new version with enhancements and updates for the language. And, this year is no exception!
ECMAScript 2021, aka ES12, released in June 2021, has some fantastic features that will make your programming more concise and readable. In this article, we will discuss some of the most noteworthy features of the new release, their benefits, and how to use them.
1. Logical Assignment Operators
Ever get tired of writing repetitive code for assignments? Exciting news! ES12 introduces the logical assignment operators to make your assignments even more concise!
Logical assignment operators help you to simplify your code by allowing you to combine logical operations with assignment operations. Let's say you want to set a variable x to "hello" when it is undefined. Earlier, you would write:
if (typeof x === "undefined") {
x = "hello";
}
With logical assignment operators, you can write this code in a much simpler form:
x ||= "hello";
Here, ||=
is a logical assignment operator, which assigns the value of the right-hand side operand ("hello") to the left-hand side operand x
if x
is falsy (null, undefined, 0, false, NaN) or undefined. The operator also returns the value of the left-hand side operand after the assignment.
Similarly, you can use the &&=
operator, which assigns the value of the right-hand side operand to the left-hand side operand if the left-hand side operand is truthy, and returns the value of the left-hand side operand after the assignment.
let y;
y &&= "world";
In this case, the &&=
operator checks if the left-hand side variable y
is truthy or not; if it is falsy, it returns false
and sets y
to the right-hand side operand "world."
2. Promise.any() method
Have you worked on projects that rely on multiple promises? ECMAScript 2021 offers a new method to make your promise handling much more efficient and easy!
The Promise.any()
method is a new feature introduced in ES12 that resolves the first promise in a sequence that resolves or rejects. Earlier, we had Promise.all()
and Promise.race()
methods to deal with multiple promises.
With Promise.any()
, you can initiate multiple promise requests and get the value or rejection of the first successful promise that is resolved. In contrast, Promise.race()
returns the value or rejection of the fastest promise that is resolved or rejected. While Promise.all()
waits for all promises to resolve or reject and returns an array of their resolutions.
Here's how to use Promise.any()
:
let promises = [
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2'),
fetch('https://jsonplaceholder.typicode.com/todos/3')
];
Promise.any(promises)
.then(result => console.log(result))
.catch(error => console.log(error));
In this example, we instantiate three promises with fetch()
to retrieve todo items from an API. Promise.any()
resolves the first promise that resolves or rejects and returns only that promise's resolved result.
3. Numeric Separators in Literal Numbers
Ever struggled with long numbers in your applications? The latest version of ECMAScript has introduced numeric separators to help keep your numbers readable!
Numeric separators are characters that are used to separate digits of a number to make it more readable. Before the introduction of numeric separators, we had to use commas or underscores in long numbers to segregate the digits. However, this made reading the numbers much harder.
ES12 has now introduced the support of binary, octal, and BigInt numeric literals with numeric separators. Let's take an example to see how to use numeric separators:
const bigNumber = 3_75_498_792n; //BigInt
const binaryNumber = 0b1010_0001_0011; //Binary
const octalNumber = 0o123_456; //Octal
const decimalNumber = 123_456_789; //Decimal
Here, you can see that we use an underscore to separate digits of the number, making it more readable.
4. String.prototype.replaceAll() method
Have you ever needed to replace all occurrences of a substring in a string, but the standard replace()
method wouldn't do the trick? The replaceAll()
function in ES12 comes to the rescue!
String.prototype.replaceAll()
is a new string method introduced in ECMAScript 2021 that replaces all occurrences of a specified substring in a given string with a new substring. It is similar to the replace()
method, but replace()
only replaces the first occurrence of a substring in a given string.
For instance, consider the following example:
const text = "The quick brown fox jumps over the lazy dog";
const newText = text.replaceAll("the", "THE");
console.log(newText); //Output: "The quick brown fox jumps over THE lazy dog"
In this example, we replace all instances of the substring "the"
with "THE"
.
5. Logical Operators for Nullish values
Have you ever got confused between null
and undefined
values while using logical operators? The latest version of ECMAScript has a new way to deal with these falsey/nullish values!
In JavaScript, null and undefined values are considered falsey or nullish values. The &&
(AND) operator and ||
(OR) operator have been used to deal with nullish values in JavaScript.
But these operators treat null
and undefined
values differently, which can lead to confusion while coding. ES12 has introduced new operators ??
(Nullish Coalescing) and ?.
(Optional Chaining) to tackle this problem.
The ??
operator evaluates the expression to the left and returns it if it's not nullish; otherwise, it returns the expression to its right. This means if the left-hand side operand has a defined value, then it returns that value, otherwise, it returns the right-hand side operand.
let a = null;
let b = a ?? "default";
console.log(b); //Output: "default"
In this example, as a
is null, the right-hand side operand "default"
is returned.
On the other hand, ?.
operator is used to check for null and undefined values while accessing the properties of an object. It returns undefined
instead of throwing a TypeError exception.
These operators help you to write more concise and accurate code by reducing the chance of errors resulting from nullish values.
6. Miscellaneous Features
ES12 also introduces several other features to make your programming experience more efficient and secure.
-
String.prototype.replaceAll()
supports regular expressions to replace all instances of a given pattern in a given string.const text = "Programming is my passion. Passionate about programming?"; const newText = text.replaceAll(/passion/gi, "love"); console.log(newText); //Output: "Programming is my love. Loveate about programming?"
-
Promise.allSettled() method: Unlike the
Promise.all()
method which waits for all promises to resolve or reject,Promise.allSettled()
waits for all promises to settle (either resolved or rejected). This means that even when a promise is rejected, the method still returns an array with the results of all promises. -
New Target: Earlier,
new.target
could only be accessed inside the constructor function to check if the function is called with new keyword or not. But in ES12, we can use it in the arrow function as well to return the constructor name.function Person() { console.log(new.target.name); } const person1 = new Person(); // output: "Person" const person2 = Person.call(person1) // output: "undefined" const createObject = () => { console.log(new.target) } createObject(); // output: undefined
Conclusion
These are some of the exciting features introduced in the latest version of ECMAScript 2021. Whether you're a beginner or an experienced programmer, these updates will make your coding more efficient and less prone to errors. So, why not dive into these new features and take your JavaScript programming skills to the next level?
Remember, the best way to learn these features is to practice them in your day-to-day programming. Happy Coding!
Editor Recommended Sites
AI and Tech NewsBest Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
AI Books - Machine Learning Books & Generative AI Books: The latest machine learning techniques, tips and tricks. Learn machine learning & Learn generative AI
Learn Rust: Learn the rust programming language, course by an Ex-Google engineer
Learn Sparql: Learn to sparql graph database querying and reasoning. Tutorial on Sparql
Software Engineering Developer Anti-Patterns. Code antipatterns & Software Engineer mistakes: Programming antipatterns, learn what not to do. Lists of anti-patterns to avoid & Top mistakes devs make
Data Migration: Data Migration resources for data transfer across databases and across clouds