New JavaScript Features in ECMA2020 That Every JavaScript Developer Should Know
In this article, I will be writing about few new features of JavaScript that is introduced in ECMA2020 . Let's discuss below features
- Dynamic Import
- Import Metadata
- Module Export
- BigInt (New Data Types)
- Regular Expression matchAll()
- globalThis Object
- nullish coalescing operator
- Optional chaining
1. Dynamic Import
The current mechanism for importing modules is based on static declarations like the following:
import * as MyModule from "./my-module.js";
This statement has a couple of constraints:
• all the code of the imported module is evaluated at the load time of the current module
• evaluating each dependent module at load time affects the performance of the application
Dynamic import solves this problem by allowing to import module dynamically. The statement accepts a module specifier as an argument and returns a promise. Also, the module specifier can be any expression returning a string. This is just like how you do it with Webpack and Babel at the moment.
You can also conditionally load code in an if-else block if you like.
If (condition)
{
const dynamicModule=await import (‘./myModule.js’)
dynamicModule.AddNumbers(2,3,4)
}
2. Import Metadata
The import.meta
object provides metadata for the current module. The JavaScript engine creates it, and its current available property is url. This property's value is the URL from which the module was loaded, including any query parameter or hash.
Consider a module, mymodule.js
<script type="module" src="mymodule.js"></script>
You can access meta information about the module using the import.meta
object: console.log(import.meta); // { url: "file:///home/user/mymodule.js" }
It returns an object with a url property indicating the base URL of the module. This will either be the URL from which the script was obtained (for external scripts), or the document base URL of the containing document (for inline scripts).
3. Module Export
Some times, developer may need to export objects imported from another module. A handy export syntax may help you, as shown in the following:
export {value} from "./mymodule.js";
export * from "./mymodule.js";
This symmetry between import and export statements is convenient from a developer experience standpoint. However, a specific case wasn't supported before these new specifications:
import * as MyModule from "./mymodule.js";
To export the MyModule namespace, you should use two statements
import * as MyModule from "./mymodule.js";
export {MyModule};
Now, you can get the same result with one statement, as shown below
export * as MyModule from "./mymodule.js";
This addition simplifies your code and keeps the symmetry between import and export statements.
4. BigInt (New Data Types)
As you know, JavaScript has only one data type for numbers: the Number
type.
This primitive type allows you to represent 64-bit floating-point numbers. Of course, it also represents integers, but the maximum representable value is 2^53
, corresponding to the Number.MAX_SAFE_INTEGER
constant.
BigInt, allows developers to have much greater integer representation in their JS code for data processing for data handling.
The new BigInt data type aims to solve these issues.
You represent a literal BigInt by simply appending the letter n to a number, as shown in this example:
const aBigInt = 9876543212223456789n;
You can also use the BigInt() constructor the same way you use the Number() constructor:
const aBigInt = BigInt("9876225432123456789");
5. Regular Expression matchAll()
matchAll
is a new method added to the String prototype which is related to Regular Expressions. This returns an iterator which returns all matched groups one after another.
const regExp = /test (\d+)/g;
const text = 'text test 1 text text test 2';
let matches = [...text.matchAll(regExp)];
for (const match of matches) {
console.log
6. globalThis Object
Accessing the global object requires different syntaxes, depending on the JavaScript environment. For example, in a browser, the global object is window
, but you cannot use it within a Web Worker. In this case, you need to use self
. Also, in Node.js the global object is global
.
The globalThis
object provides a standard way of accessing the global object across different JavaScript environments. So, now you can write your code in a consistent way, without having to check the current running environment
globalThis.setTimeout==window.setTimeout
true
7. nullish coalescing operator
The nullish coalescing operator treats undefined and null as specific values and so does the optional chaining operator ( ?.) which is useful to access a property of an object which may be null or undefined. The definition of 'nullish coalescing expression' in that specification.
Nullish coalescing adds the ability to truly check null values instead of false values.
In JavaScript, a lot of values are false, like empty strings, the number 0, undefined, null, false, NaN, and so on.
However, a lot of times you might want to check if a variable is null – that is if it is either undefined or null, like when it's okay for a variable to have an empty string, or even a false value.
To overcome these potential issues, now you can use the nullish coalescing operator (??).
False ?? ‘some value’ – return false
Null?? ‘some value’ – return some value
8. Optional chaining
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
Optional chaining syntax allows you to access deeply nested object properties without worrying if the property exists or not. If it exists, great! If not, undefined will be returned. This not only works on object properties, but also on function calls and arrays.
Consider the following example:
const txtName = document.getElementById("txtName");
const name = txtName ? txtName.value : undefined;
You get the textbox with txtName
as its identifier from the current HTML document. However, if the HTML element doesn't exist in the document, the txtName
constant will be null
. So, before accessing its value property, you have to make sure that txtName
is not null or undefined.
The optional chaining operator (?.) allows you to have a more compact and readable code, as shown below:
const txtName = document.getElementById("txtName");
const name = txtName?.value;
As in the previous example, the name constant will have the the value of txtName.value
if txtName
is not null
or undefined
; undefined
otherwise.
That's all for this Blog developers and with that, it's a wrap! I hope you found the article useful.
I create content about Programming, and Productivity, If this is something that interests you, please share the article with your friends and connections.
Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!
I would strongly recommend you to Check out my YouTube Channel youtube.com/c/codeasitis where i post programming video and don't forget to subscribe to my Channel. I would love to connect with you at Twitter ( twitter.com/codeasitis1 ) | Instagram ( instagram.com/codeasitis )
See you in my next Blog article, Take care!!