Learning ECMAScript 7 features in Node.js console

Marco Minetti | Sep 10, 2015

nodejs console ecmascript7 javascript snippet learning babeljs
Article Goal

This article offers a list of code examples to experience and learn experimental ECMAScript 7 features. You will get effective code snippets that simply work out of the box in the Node.js console.

The new ECMAScript 6 has been ratified in June 2015 but many draft specification proposals for the further ECMAScript 7 has been already submitted.

Node.js console embeds the amazing Babel.js compiler to provide support for "next generation of Javascript today" (claim of Babel.js project).

The great news is that, since the very beginning, Babel.js provides support beyond the ECMAScript 6 and currently backports some experimental features from the ECMAScript 7.

Babel.js is still under active development and experimental ECMAScript 7 features may vary during time until their standardization.

  

Here follows a table with brief explanations and examples related to the experimental ECMAScript 7 features.

To start learning and try the examples, you can easily get Node.js console through the installation tutorial at "Console: handling Javascript Node.js runtime like a pro".

  

Features Examples

Exponentiation Operator

compact ** operator

// x ** y

let squared = 2 ** 2;
// same as: 2 * 2

let cubed = 2 ** 3;
// same as: 2 * 2 * 2
 
let a = 2;
a **= 2;
// same as a = a ** 2

Async Functions

natural asynchronous function implementation

// define global sleep function that returns a promise
global.sleep = function(error, ms=5000) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      if (!error) {
        resolve();
      } else {
        reject(error);
      }
    }, ms);
  });
};
 
// define async function
async function verboseSleep(...args) {
  console.log('falling asleep...');
  // await operator
  return await sleep(...args);
}

Await Operator

await operator for asynchronous programming

Warning

Pay attention to the enclosing brackets in most of the cases.

// define global function that returns a promise resolving into a value
global.call = function(result, error, ms=1000) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      if (!error) {
        resolve(result);
      } else {
        reject(error);
      }
    }, ms);
  });
};
 
// usage examples (syntax)
what = await call('hello');
if ((await call(true)) === true){ console.log('world'); };
if (await call(false)) { console.log('never'); };
a = (await call(true)) ? true : false
b = ((await call(false)) === true) ? true : false;
c = (await call()) || (await call(null)) || '!';
d = { 'e': await call('now'), 'now': new Date() };
f = d[await call('now')];
try {
  await call(null,new Error('oops'));
} catch (e) {
  console.error(e);
}
var list = [];
for (var i = await call(0); (await call(i)) < 10; (await call(i++))) {
  list.push(await call(i));
}
await (async function(g){
  await call(g);
  return g;
})();

Await* Operator (parallelism)

await* operator for parallel asynchronous programming

Warning

Implementation is missing for Array iterative methods, polyfill support will be available soon.

global.transform = function(what, ms=1000) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
	  console.log(`processing ${what}`);
      resolve(what * 2);
    }, ms * what);
  });
};
 
async function doTransform() {
  var nums = [1, 2, 3, 4, 5];
  return await* nums.map(async (item, index) => {
    return {
      index: index, 
      value: await transform(item)
    }
  });
}
 
await doTransform();

Destructuring Enhancement (with rest/spread properties)

destructing support for object properties

// rest properties
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }
 
// spreading properties
let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }
(more are to come, this article will be kept updated)  

  

Troubleshooting Node.js console

If you are experiencing problems with Node.js console module, please check its dedicated troubleshooting section.

ECMAScript 6 specific issues are reported below.

Some ECMAScript features not working

Remember that the support for some latest and, more important, experimental ECMAScript features can't be implemented without natives.

Please check on Babel.js documentation and experimental usage whether the feature is supported and whether limits applies.

  

If you are experiencing any other problem, please contact me so we can extend this section.

You can also report bugs or feature requests directly at the GitHub project page.

  

Further readings and related articles