
It’s hard to keep track of what’s new in the world of JavaScript. It’s even more difficult to find code examples of the cutting edge of JS. At the latest meeting of TC39, new features will make into the “ECMAScript 2018 Language Specification“. All the proposals have reached stage 4 which is the “finished stage“. A list of the Stage-4 proposals are available on GitHub.
Rest/Spread Properties
Rest/Spread properties allow you to collect the remaining properties of an object into a new object when destructuring.
- You could use rest to help you extract only properties you need
// Extracts name and age, and stores the rest of the details in ‘etc’ variablelet { name, age, …etc } = {name: ‘xyz’,age: ’25’,race: ‘Vulcan’};name; //xyzage; //25etc; // { race: ‘Vulcan’ }
- You could also remove unwanted items
// Use rest destructuring to extract age, and keep the rest of details in //cleanObjlet { age, …cleanObj } = {name: ‘xyz’,age: ’25’,race: ‘Vulcan’,};cleanObj; // { name: ‘xyz’, race: ‘Vulcan’ }
- Spread properties are similar to Rest the difference being you use spread to create (restructure) new objects.
//Merge person and detailsconst person = { fName: ‘xyz’ , age: ’25’};const details = { name: ‘abc’, amount: ‘$100’ }; //Extract person’s and account’s properties via spread operator and add it // to a new objectconst personAcc = { …person, …account };personAcc; // { fName: ‘xyz’ , age: ’25’, name: ‘abc’, amount: ‘$100’ } ProTip: The rest operator is used on the left-side of the equal to symbol while the spread operator is used on the right-side of the equal to symbol.
Asynchronous Iteration
This is a very useful feature, which lets you create loops of aysnc code. With this feature a new “for-wait-of” loop is added which lets you call async functions that return promises (or Arrays with multiple promises) in a loop. const promises = [ new Promise(resolve => resolve(1)), new Promise(resolve => resolve(2)), new Promise(resolve => resolve(3)),]; //Before:// for-of uses regular sync iterator// Doesn’t wait for promise to resolveasync function test1() { for (const obj of promises){ console.log(obj); //Logs 3 promise objects }} // After:// for-await-of uses Async iterator// Waits for Promise to resolve for each loopasync function test2(){ for await (const obj of promises) { console.log(obj); //Logs 1,2,3 }} test1(); // promise, promise, promisetest2(); //1,2,3 … prints values
Promise.prototype.finally()
finally() is the latest instance method that was added to Promise. The logic is to allow running a callback after either resolve or reject to clean things up. The finally callback is called without any value and is always executed no matter what. Here are the various cases:
- finally() in resolve case
//Resolve Case …let started = true;let myPromise = new Promise (function(resolve, reject)) {resolve(‘perfect’);}).then(val => {console.log(val); //logs ‘all good’}).catch(e => {console.log(e); //skipped}).finally(() => {console.log(‘This always gets executed’);started = false; //clean up});
- finally() in reject case
//Reject Case …let started = true;let myPromise = new Promise (function(resolve, reject)) {resolve(‘reject’);}).then(val => {console.log(val); //logs ‘rejected’}).catch(e => {console.log(e); //skipped}).finally(() => {console.log(‘This always gets executed’);started = false; //clean up});
Regular Expressions Related Features
- ‘dotall’ flag for Regular Expressions
Currently in RegEx, although the dot(“.”) is supposed to match a single character, it doesn’t match new line characters like \n \r \f etc.For example://Before /first.second/.test(‘first\nsecond’); //falseThis enhancement makes it possible for the dot operator to match any single character. In order to ensure this doesn’t break anything, we need to use \s flag when we create the RegEx for this to work.//ECMAScript 2018 /first.second/s.test(‘first\nsecond’); //true Notice: /s
- RegExp Named Group Captures 🔥
This enhancement brings a useful RegExp feature from other languages like Python, Java and so on called “Named Groups.” This features allows developers writing RegExp to provide names (identifiers) in the format(?<name>…) for different parts of the group in the RegExp. They can then use that name to grab whichever group they need with ease.const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u; const result = pattern.exec(‘2017-01-25’);// → result.groups.year === ‘2017’// → result.groups.month === ’01’// → result.groups.day === ’25’
- Unicode Property Escapes
This allows us to access these Unicode character properties natively via regular expressions. For example, the pattern \p{Script_Extensions=Armn} matches every symbol that is used in the Armenian script.const regexGreekSymbol = /\p{Script_Extensions=Greek}/u; regexGreekSymbol.test(‘π’); // → true
Do note that all these features aren’t readily available in all browsers. Since they are Stage-4 it means that the vendors should now implement them. You could have a look at the full list of finished proposals here.