Original link: www.sitepoint.com/es2018-whats-new/
In this article, I'll cover the new features of JavaScript introduced through ES2018 (ES9), as well as examples of what they do and how they are used.
JavaScript (ECMAScript) is a constantly evolving standard that is implemented by many vendors on multiple platforms. ES6 (ECMAScript 2015) is a large version that took six years to complete. The new annual release process has been developed to streamline processes and add functionality faster. ES9 (ES2018) is the latest version when writing this article.
The technical committee, TC39, consists of parties, including browser vendors, who drive JavaScript proposals on a rigorous path to advancement:
Stage 0:strawman--The original idea of the submission.
Stage 1:proposal (proposal)-a formal proposal, advocated by at least one member of the TC39, which includes an API case.
Stage 2:draft (draft)-the initial version of the functional specification, which contains two experimental implementations of the functional specification.
Stage 3:candidate (Candidate) – Proposal specification through review and collection of feedback from vendors
Stage 4:finished (complete)--the proposal is ready to join the ECMAScript, but it may take longer to reach the browser or Nodejs
ES2016
ES2016 proves the standardization process by adding two small functions:
- The array contains the () method that returns true or False when the array contains a value, and
Take the exponentiation operator, with ... Same. a ** b
Math.pow(a, b)
ES2017ES2017 offers more new features:
- Asynchronous functions enable clearer promise syntax
Object.values()
Extracts an array of values from an object that contains a name-value pair
Object.entries()
, returns an array of sub-arrays containing the names and values in the object
Object.getOwnPropertyDescriptors()
The returned object is scoped to another object's own property descriptor (,,,,, .value
.writable
).get``.set``.configurable``.enumerable
padStart()
And, two elements of a string fillpadEnd()
- object definitions, array declarations, and trailing commas for function argument lists
SharedArrayBuffer
and Atomics
read and write shared memory locations (disabled in response to the Spectre vulnerability).
For more information, see what's New in ES2017.
ES2018
ECMAScript 2018 (or ES9, if you prefer the old notation) is now available. The following features have reached phase 4th, but the work implementation of the browser and runtime will be incomplete at the time of writing this article.
Asynchronous iterations
At some point in the asynchronous/wait process, you will try to invoke the Async function within the synchronization loop. For example:
async function process(array) { for (let i of array) { await doSomething(i); }}
It won't work. This also does not:
async function process(array) { array.forEach(async i => { await doSomething(i); });}
The loops themselves remain synchronized and are always completed before their internal asynchronous operations.
ES2018 introduces an asynchronous iterator that, like a regular iterator, simply returns a promise. Therefore, keywords can be used with loops to run asynchronous operations serially. Example: Next () awaitfor
async function process(array) { for await (let i of array) { doSomething(i); }}
Promise.finally ()
The promise chain can succeed and reach final or failed and trigger blocking. In some cases, regardless of the outcome, you want to run the same code-for example, Cleanup, delete dialog box, close database connection, etc... then (). catch ()
The prototype allows you to specify a place for the final logic instead of copying it at the end and:. finally (). then (). catch ()
function doSomething() { doSomething1() .then(doSomething2) .then(doSomething3) .catch(err => { console.log(err); }) .finally(() => { // finish here! });}
Rest/spread Property
ES2015 introduces the rest parameter and extension operator. Three dots (...). ) is used only for arrays. The rest parameter syntax allows us to represent the parameters of a pudding number as an array.
restParam(1, 2, 3, 4, 5);function restParam(p1, p2, ...p3) { // p1 = 1 // p2 = 2 // p3 = [3, 4, 5]}
The spread operator works in the opposite way and converts the array to a separate argument that can be passed to the function. For example, given any number of arguments, the highest value is returned: Math.max ()
const values = [99, 100, -1, 48, 16];console.log( Math.max(...values) ); // 100
ES2018 provides an array of rest parameters () and expansion operators for object deconstruction, a simple example:
const myObject = { a: 1, b: 2, c: 3};const { a, ...x } = myObject;// a = 1// x = { b: 2, c: 3 }
Or you can use it to pass values to the function:
restParam({ a: 1, b: 2, c: 3});function restParam({ a, ...x }) { // a = 1 // x = { b: 2, c: 3 }}
As with arrays, the rest parameter can only be used at the end of a declaration. In addition, it applies only to the top level of each object and cannot be applied if the object is absconded.
Extension operators can be used within other objects, for example:
const obj1 = { a: 1, b: 2, c: 3 };const obj2 = { ...obj1, z: 26 };// obj2 is { a: 1, b: 2, c: 3, z: 26 }
You can use the spread operator to clone an object (), but be aware that you can only get a shallow copy. If the property contains another object, the clone references the same object. Obj2 = {... obj1};
Regular expression named capturing group (Regular expression Named capture Groups)
A JavaScript regular expression can return a matching object-similar to an array of values, containing a matching string. For example, to parse the date in YYYY-MM-DD format:
const reDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/, match = reDate.exec('2018-04-30'), year = match[1], // 2018 month = match[2], // 04 day = match[3]; // 30
It is difficult to read, and even more correct the expression may change the matching object index.
ES2018 allows you to use symbol-named groups immediately after you begin capturing parentheses. For example:?
const reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/, match = reDate.exec('2018-04-30'), year = match.groups.year, // 2018 month = match.groups.month, // 04 day = match.groups.day; // 30
Any unmatched named groups set their properties to undefined.
Named captures can also be used in methods. For example, convert a date to US mm-dd-yyyy format: replace ()
const reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/, d = '2018-04-30', usDate = d.replace(reDate, '$<month>-$<day>-$<year>');
Regular expression Reverse assertion (lookbehind)
JavaScript currently supports forward-looking assertions in regular expressions. This means that a match must be made, but nothing is captured, and the assertion is not included in the entire matching string. For example, to capture a currency symbol from any price:
const reLookahead = /\D(?=\d+)/, match = reLookahead.exec('$123.89');console.log( match[0] ); // $
ES2018 introduces work in the same way but matches the previous reverse assertion (lookbehind) so that I can ignore the currency symbol and simply capture the price of the number:
const reLookbehind = /(?<=\D)\d+/, match = reLookbehind.exec('$123.89');console.log( match[0] ); // 123.89
The above is a positive reverse assertion, a non-digital \d must exist. Similarly, there is a negative reverse assertion, which indicates that a value must not exist, for example:
const reLookbehindNeg = /(?<!\D)\d+/, match = reLookbehind.exec('$123.89');console.log( match[0] ); // null
Regular expression Dotall mode
The midpoint of the regular expression. Match any single character except carriage return, and Mark s changes this behavior to allow the presence of a line terminator, for example:
/hello.world/s.test('hello\nworld'); // true
Regular Expression Unicode property escape
So far, it is not possible to natively access Unicode character properties in regular expressions. ES2018 added Unicode attribute escape-a regular expression that sets the (Unicode) flag in forms and-. Example: \p{...} \p{...} U
const reGreekSymbol = /\p{Script=Greek}/u;reGreekSymbol.test('π'); // true
Template text Adjustment
Finally, all syntax restrictions related to escape sequences in template text are removed.
Before starting a Unicode escape, start with a \u
\x
hexadecimal escape, \
followed by a number that begins an octal escape. This makes it impossible to create a specific string, such as a Windows file path C:\uuu\xxx\111
. For more details, refer to template strings.
This is ES2018, but ES2019 's work has begun. Do you have any special features you want to see next year?
Translator Reference