ES8: key innovations

Original author: Dor Moshe
  • Transfer
In general, the topic of innovation in EcmaScript is constantly on the bucket. This is far from accidental, since new standards, for some time now, are published annually. The ES6 standard appeared in 2015, ES7 in 2016. But hardly anyone will immediately remember when ES5 was released, as it happened in 2009, before the era of rapid growth and development of JavaScript. Perhaps every JS developer oversees 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 immediately go to the web version or to the PDF version of the new standard. In addition, useful information about ES8 features can be found on the MDN website.whose materials were used in the preparation of this review. Those who want to quickly get acquainted with the main innovations of ES8 and look at code examples are invited to cat.

Adding lines to a given length


This feature is implemented using two methods of the object String: padStart()and padEnd(). The words “Start” and “End” in the names of functions hint at their role in the processing of strings. Namely, they allow you to set the parameters for padding strings until they reach the specified length. The method padStart()supplements the line from its beginning (left), padEnd()- from the end (right). Lines can be supplemented with given 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, optional padString, is the line that will complement the original line. Without specifying this parameter, a space will be used for padding. If the length of the string to which one of these methods is applied exceeds the specified length, the original 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 method Object.values()returns an array of its own enumerated properties of the object passed to it in the same order in which the loop does it for…in. The syntax of the method is extremely simple:

Object.values(obj)

A parameter objis the object whose properties are to 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 method Object.entries()returns an array of its own enumerated object properties in the format [ключ, значение], in the same order as Object.values(). The syntax of the method is similar 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 method Object.getOwnPropertyDescriptors()returns a handle to the native property of the passed object. Own property is defined directly in the object, and not obtained through the prototype chain. Here is the syntax of the method:

Object.getOwnPropertyDescriptor(obj, prop)

An argument objis an object whose property data needs to be obtained, argument propis the name of the property whose descriptor interests us. As a result of successful execution of this method, an object will be returned in which the following keys can be:

  • configurable — true- if the type of the property descriptor can be changed and if the property can be removed from the object containing it, otherwise false.

  • enumerable- true- if the property is available when listing the properties of the object, otherwise - false.

  • writable- true- if the value associated with the property can be changed, otherwise false(for data descriptors)

  • get- a function that returns the value of the property, or if it is absent - undefined(for access descriptors)

  • set- a function that changes the value of a property, or if it is absent - undefined(for access descriptors)

  • value - The value associated with the property (for data descriptors).

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 language mechanisms such as decorators .


Browser Support (MDN)

Trailing commas in function parameters


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

Trailing commas are now supported in function parameter lists. Previously, the appearance of a comma at the end of the parameter list caused an error SyntaxError. Now this does not happen. Here is an example of declaring a function that has a trailing comma in its parameter list:

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

A trailing comma may appear when the function is called:

es8(10, 20, 30,);

Asynchronous functions


The keyword asyncallows you to define an asynchronous function that returns an AsyncFunction object . Inside, their work is much like the way 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();

The call sayHello()will lead to the output of the line “ Hello, es8” to the log with a delay of 2 seconds, while the main thread of execution 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 calls console.log()are made one after another, and the asynchronous function, without blocking the main thread, is executed after 2 seconds.

Note that asynchronous functions always return promises, and the keyword awaitcan only be used in functions defined using the keyword 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 data integrity and predictability of the results of operations. That is, for example, to guarantee that a certain operation will be completed before another begins, or that a certain operation will not be interrupted. Similar functionality in ES8 is provided by new language mechanisms. Firstly, this is a SharedArrayBuffer object , and secondly, an Atomics object containing a set of static methods.

An object Atomicscannot be used as a constructor; in this regard, it is similar to Math. There are object methodsAtomics, which allow you to perform various safe operations with elements of typed arrays used to access objects SharedArrayBuffer. Among them, for example, is a method Atomics.add()for adding a specified number to what is stored at a given position in an array. There are in Atomicsand methods for organizing lock management, in particular, this Atomics.wait()and Atomics.wake().


Browser Support (MDN)

Let's look into the future: expanding the capabilities of tagged template strings in ES9


ES6 introduces tagged template strings . The output of such patterns can be changed using functions, subjecting it to some logic that we need. For instance:

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 estha number is written in 8, the function will return " ES 8 is awesome". If in esthwill 7, then the function will return " ES 7 is good".

However, tagged templates still have some limitations . They are associated with escape sequences. For example, this applies to substrings starting with \uor \x. In particular, for example, the \uUnicode character code should follow, otherwise an error message will appear. It is expected that this restriction will be removed in ES9.


Browser Support (MDN)

Summary


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

Dear readers! Are you using ES8 innovations?

Also popular now: