3 useful features of ECMAScript 2019 (ES2019) that you can use right now

Tram Ho

Not long ago, ECMAScript 2019 (or ES2019) was released to the public. In it, the dev brothers are also looking forward to see what is new and superior to the old versions, as well as when these features can be used on browsers. In this article, I list three features that are supported on the latest versions of Firefox and Chrome. That means developers can use these features now.

1. Object.fromEntries ()

Converting from Object to Array is relatively easy, because Javascript’s default Object object provides us with an entry entries() or Object.entries() . For example:

But what if we want to convert an Array back to an Object (or vice versa)? There are several Javascript libraries that have assisted us in this, such as _.fromPairs() ‘s _.fromPairs _.fromPairs() method . However, downloading a large library just to use a feature has never been a good idea. Understanding this problem, the latest version of Javascript (ES2019) has added a new method that we can convert from Array to Object that is Object.fromEntries() :

2. trimStart () and trimEnd ()

Javascript provides us with a method called trim() , which allows us to remove leading and trailing spaces from a string:

However, sometimes we just want to remove the space at the beginning (or at the end) of that string. Now, we can use trimStart() and trimEnd() with trimStart() remove the leading space and trimEnd() remove the space at the end of the string. For example:

3. flat () and flatMap ()

The flat() allows us to reduce the number of levels of a multidimensional array (an array containing other arrays). It takes the input parameter that is the maximum number of levels we want to reduce from the original, the default is 1. The flat() will reduce the number of arrays of the array by 1 and flat(2) will reduce the number of levels. of the array down 2 acute from the root.

Besides, flat() also helps us remove empty elements in the array:

In addition, we also have the method flatMap() , a combination of map() and flat() . First, flatMap() creates a new array with values ​​taken from a given array, and then it decreases the array’s number of levels. For example:


Reference: https://blog.logrocket.com/5-es2019-features-you-can-use-today/

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo