New Features in ECMAScript 2018

Posted By : Satish Joshi | 25-Nov-2018

 

ES2018 brings a lot of advance feature and it's an enhancement to JS engines. Here we discuss some of its key features in detail :

 

ES2018 Features :

 

1. Shared Memory -

 

Earlier, To share the data between the main JS thread and web-workers, we had to copy the data and send it to the other thread using postMessage. But not anymore as this feature helps in to manage the memory by themselves instead of letting JS engine manage memory which is done by a new global object called SharedArrayBuffer which stores the data in a shared memory space so that the data is accessible by both main Js thread and web-worker threads.

 

To help avoid race conditions which are due to sometimes sharing memory between threads, the “Atomics” global object is introduced which provides various methods to lock the shared memory when a thread is using its data.The main purpose is to bring multi-threading feature to JS for better performance and concurrency. 

 

2. Asynchronous Iteration -

 

To get rid of using the async/await inside the synchronous loop. As now it allows us to create loops of async code with ease!

Earlier we use like this :

async function process(array) {
  for (let i of array) {
    await doSomething(i);
  }
}

Now after this feature we will use “for-await-of” which allows us to call async functions that return promises (or Arrays with a bunch of promises) in a loop. It waits for each promise to resolve before doing to the next loop. Here's the example :

async function process(array) {
  for await (let i of array) {
    doSomething(i);
  }
}

 

3.Promise.prototype.finally() -

 

finally() is a new instance that is added into ES2018 which allow running a callback after either resolve or reject. This method allows you to specify final logic in one place or finalizes the whole promises implementation like if you want to clean up, remove a dialog, close a database connection etc.

 

Example :

function doSomething() {
  doSomething1()
  .then(doSomething2)
  .then(doSomething3)
  .catch(err => {
    console.log(err);
  })
  .finally(() => {
    // finish here!
    // clean up
  });
}

 

4.Rest/Spread Properties -

 

Rest operator ... (three dots) allows us to extract the object properties while Spread is also used with the same notation as rest operator the only difference is that you use spread to create or restructure new objects.  Also, the spread operator is used on the right side of the equals sign. The rest is used on the left side of the equals sign.

 

Rest property Example :

//Extract the firstName and age
// and store the rest of the items in remaining variable
let {firstName, age, ...remaining} = {
        firstName: 'john',
        lastName: 'smith',
        age: 20,
        height: '5.10'
};

firstName; // john
age; // 20
remaining; // {lastName: 'smith', height: '5.10'}

 

Spread Property Example :

// Merge key into obj object
let key = { a: 10, b: 20, c: 30 };
let obj = { ...key, z: 40 };
// obj is { a: 10, b: 20, c: 30, z: 40 }

 

Note: Spread property could be used to clone the objects but be aware you get only shallow copies as the clone will refer to the same object if the property holds another object.

 

5. Regular Expression related features -

 

ES2018 include 4 RegExp related proposals and here we discuss one by one :

 

Regular Expression Named Capture Groups :

 

This feature allows writing RegExp by providing names (identifiers) in the format (?<name>...).  Here's the example :

const
  reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/,
  match  = reDate.exec('2018-11-25'),
  year   = match.groups.year,  // 2018
  month  = match.groups.month, // 11
  day    = match.groups.day;   // 25

In the above example, we used (?<year>) (?<month>) and (?<day>) names to group different parts of the date RegEx.The resulting object will now contain a groups property with properties year, month, and day with corresponding values.

 

"dotall" flag for Regular Expression :

 

This feature of regExp allows matching any single character except carriage returns with the help of dot (.) operator. The S flag ensures that it doesn't break anything or we can say it matches the character including line terminators. Here's the example :

/hello.world/s.test('hello\nworld');

 

RegExp Lookbehind Assertions :

 

In this feature it allows (?<=...) to look behind for positive assertions and (?<!..) to look behind for a negative assertion. It ensures that a pattern is or isn't preceded by another.

 

Example For Positive Assertion :

Let's take a scenario, the # sign exists before the word winning i.e; #winning but you want the regex to return just the string "winning". Here is how you'd write it.

'#winning'.match(/(?<=#).*/)[0];   //  Only 'winning' word will return

 

Example For Negative Assertion :

Let’s say we want to extract numbers from lines that have € signs and not $ signs before those numbers. Its main purpose is to set that a value must not exist.

'A gallon of milk is $3.00'.match(/(?<!\$)\d+\.?\d+/);  // It will return null because of $ sign before the amount.

'A gallon of milk is €3.00'.match(/(?<!\$)\d+\.?\d+/)[0];  // It will return 3.00 because $ sign was not before the amount.

 

Regular Expression Unicode Property Escapes :

 

ES2018 adds Unicode property escapes — in the form \p{...} and \P{...} (which is used negate the matches) that have the u (Unicode) flag set which basically helps to match with the other languages like Hindi, Greek and so on. So that's where Unicode property Escapes come in.

 

Example :

Devanagari can be used for various Indian languages like Marathi, Hindi, Sanskrit, and so on. So it matches multiple Hindi character in this example.

/^\p{Script=Devanagari}+$/u.test('??????');  // true 

/\p{Script_Extensions=Greek}/u.test('π'); // The following matches a single Greek character so it will also return true.

//The following matches an Emoji character
/\p{Emoji}/u.test('??'); //true

 

Further, the Unicode database stores various types of Emojis under the boolean properties Emoji, Emoji_Component, Emoji_Presentation, Emoji_Modifier, and Emoji_Modifier_Base with property values as `true`. So we can search for all Emojis by simply selecting Emoji to be true.

 

Thank You !

About Author

Author Image
Satish Joshi

Satish has experience on web development believes in hard work and dedication. He is friendly and an honest person.

Request for Proposal

Name is required

Comment is required

Sending message..