πŸ“œ ⬆️ ⬇️

ES8: major innovations

In general, the subject of innovations in EcmaScript is constantly on the ear. This is far from coincidental, since new standards, for some time now, are published annually. The ES6 standard appeared in 2015, ES7 - in 2016. But hardly anyone remembers immediately when ES5 came out, as it happened in 2009, before the era of rapid growth and development of JavaScript. Perhaps every JS-developer is watching the development of the language. Today it's time to talk about what ES8 brought us.

image

If you are not looking for easy ways - you can go directly to the web version or to the PDF version of the new standard. In addition, useful information about the capabilities of ES8 can be found on the website of MDN , the materials of which were used in the preparation of this review. Those who want to quickly familiarize themselves with the main innovations of ES8 and take a look at the code examples, we invite under the cat.

Addition of lines to the set length


This feature is implemented using two methods of the String object: padStart() and padEnd() . The words "Start" and "End" in the function names allude to their role in handling strings. Namely, they allow you to set the parameters for complementing the lines until they reach a specified length. The padStart() method complements the string from its beginning (left), padEnd() from the end (right). Lines can be supplemented with specified single characters, other lines, or, by default, spaces. Here is the syntax of the functions in question:
')
 str.padStart(targetLength [, padString]) str.padEnd(targetLength [, padString]) 

As you can see, the first parameter of these functions is targetLength . It represents the target length of the resulting string. The second parameter, an optional padString , is a string that will complement the source string. Without this parameter, the space will be used for the addition. If the length of the string to which one of these methods is applied exceeds the specified length, the source string remains unchanged.

Here are some examples:

 'es8'.padStart(2);          // 'es8' 'es8'.padStart(5);          // '  es8' 'es8'.padStart(6, 'woof');  // 'wooes8' 'es8'.padStart(14, 'wow');  // 'wowwowwowwoes8' 'es8'.padStart(7, '0');     // '0000es8' 'es8'.padEnd(2);          // 'es8' 'es8'.padEnd(5);          // 'es8  ' 'es8'.padEnd(6, 'woof');  // 'es8woo' 'es8'.padEnd(14, 'wow');  // 'es8wowwowwowwo' 'es8'.padEnd(7, '6');     // 'es86666' 


Browser Support (MDN)

Methods Object.values ​​() and Object.entries ()


The Object.values() method returns an array of the enumerated properties of the object passed to it in the same order in which the for…in loop does it. The method syntax is extremely simple:

 Object.values(obj) 

The obj parameter is the object whose properties should be obtained. It can be an object or an array (in other words, an object with indices like [ 10, 20, 30] -> { 0: 10, 1: 20, 2: 30 } ). Here is a sample code:

 const obj = { x: 'xxx', y: 1 }; Object.values(obj); // ['xxx', 1] const obj = ['e', 's', '8']; //   ,   { 0: 'e', 1: 's', 2: '8' }; Object.values(obj); // ['e', 's', '8'] 


Support for Object.values ​​() in browsers (MDN)

The Object.entries() method returns an array of the object's own enumerated properties in the format [, ] , in the same order as Object.values() . The syntax of the method is similar to Object.values() , and the rest of these methods are similar:

 Object.entries(obj) 

Here are some examples:

 const obj = { x: 'xxx', y: 1 }; Object.entries(obj); // [['x', 'xxx'], ['y', 1]] const obj = ['e', 's', '8']; Object.entries(obj); // [['0', 'e'], ['1', 's'], ['2', '8']] const obj = { 10: 'xxx', 1: 'yyy', 3: 'zzz' }; Object.entries(obj); // [['1', 'yyy'], ['3', 'zzz'], ['10': 'xxx']] Object.entries('es8'); // [['0', 'e'], ['1', 's'], ['2', '8']] 


Support for Object.entries () in browsers (MDN)

Object.getOwnPropertyDescriptors () method


The Object.getOwnPropertyDescriptors() method returns a handle to the property of the passed object. Own property is defined directly in the object, and not obtained through a chain of prototypes. Here is the syntax of the method:

 Object.getOwnPropertyDescriptor(obj, prop) 

The obj argument is an object, the data on which property must be obtained, the argument prop is the name of the property whose handle we are interested in. As a result of successful execution of this method, an object will be returned, which can contain the following keys:


Here is a sample code:

 const obj = { get es8() { return 888; } }; Object.getOwnPropertyDescriptor(obj, 'es8'); // { //   configurable: true, //   enumerable: true, //   get: function es8(){}, //- //   set: undefined // } 

Data descriptors are very important for such language mechanisms as decorators .


Browser Support (MDN)

Trailing commas in function parameters


Using trailing commas can simplify code editing and make it easier to work with version control systems. A similar opportunity was already present in the language for array literals (from the very beginning) and objects (starting with ES5). For example: [10, 20, 30,] and { x: 1, } .

The trailing commas are now supported in function parameter lists. Previously, a comma at the end of the parameter list caused a SyntaxError error. Now this is not happening. Here is an example of a function declaration, in the parameter list of which there is a trailing comma:

 function es8(var1, var2, var3,) { // ... } 

The trailing comma can also appear when calling a function:

 es8(10, 20, 30,); 

Asynchronous functions


The async allows you to define an asynchronous function that returns an AsyncFunction object. Inside, their work is very similar to how generators work.

Here is a sample code:

 function fetchTextByPromise() { return new Promise(resolve => {   setTimeout(() => {     resolve("es8");   }, 2000)); }); } async function sayHello() { const externalFetchedText = await fetchTextByPromise(); console.log(`Hello, ${externalFetchedText}`); // Hello, es8 } sayHello(); 

Calling sayHello() will result in the output of the string β€œ Hello, es8 ” to the log with a delay of 2 seconds, while the main execution thread is not blocked. Here's what it looks like:

 console.log(1); sayHello(); console.log(2); 

In the console, after executing this code, the following will appear:

 1 //  2 //  Hello, es8 //  2  

As you can see, two console.log() calls are executed one by one, and the asynchronous function, without blocking the main thread, is executed after 2 seconds.

Note that asynchronous functions always return promises, and the await keyword can only be used in functions defined using the async .


Browser Support (MDN)

Shared memory and Atomics object


If several threads use shared memory, they can simultaneously write data to it and read data from it. Atomic operations allow you to ensure data integrity and predictability of the results of operations. That is, for example, to ensure that a certain operation is completed before another begins, or that a certain operation is not interrupted. Similar functionality in ES8 is provided by new language mechanisms. The first is the SharedArrayBuffer object, and the second is an Atomics object containing a set of static methods.

The Atomics object cannot be used as a constructor, it is, in this respect, similar to Math . There are Atomics object methods that allow you to perform various safe operations on elements of typed arrays that serve to access SharedArrayBuffer objects. Among them, for example, the Atomics.add() method for adding a specified number to what is stored in a given array position. There are methods in Atomics for managing locks, in particular, Atomics.wait() and Atomics.wake() .


Browser Support (MDN)

Looking Ahead: Empowering Tagged Template Strings in ES9


In ES6, tagged pattern strings have appeared. The output of such patterns can be changed with the help of functions, subjecting it to some logic that we need. For example:

 const esth = 8; helper`ES ${esth} is `; function helper(strs, ...keys) { const str1 = strs[0]; // ES const str2 = strs[1]; // is let additionalPart = ''; if (keys[0] == 8) { // 8   additionalPart = 'awesome'; } else {   additionalPart = 'good'; } return `${str1} ${keys[0]} ${str2} ${additionalPart}.`; } 

If esth contains the number 8 , the function will return β€œ ES 8 is awesome ”. If esth is 7 , the function will return β€œ ES 7 is good ”.

However, some restrictions still apply to tagged patterns. They are associated with escape sequences. For example, this applies to substrings beginning with \u or \x . In particular, for example, after \u Unicode character code must follow, otherwise an error message will appear. It is expected that in ES9 this restriction will be removed.


Browser Support (MDN)

Results


JavaScript is a language that is used in an innumerable set of working web projects, and it is constantly updated. This process is perfectly organized and balanced. At the last stage of adopting innovations, they are approved by the TC39 committee, after which they are implemented by the developers of JS engines. I must say that most ES8 innovations already support TypeScript, they are supported by many browsers, in some cases polyfills help, so new JavaScript features can be put into action right now.

Dear readers! Do you use ES8 innovations?

Source: https://habr.com/ru/post/332998/


All Articles