ES6 Babel(ing)

ECMA Script 6 is the latest JavaScript technology enhancement released in 2015. Lets look at the basic features of ECMA6 with compared to old JavaScript.

  • let the var begin – ‘let’ is new keyword
  • use arrows not guns – arrow(=>) functions

Ex:

let myFunction = (input1, input2) => {return input1 + input2}

which is similar to this

var myFunction = function(input1, input2){
return input1 + input2
}

console.log(myFunction(2,4))

But how I compile new ECMA6

Solution is Babel (https://babeljs.io/)
First lets create a workspace for our ECMA6 work.

mkdir es6 && cd es6

Create a empty file .babelrc in the working directory.

vim .babelrc

and paste below content

{
"presets": ["es2015"]
}

Then we will install babel-cli in the working directoty and install es2015 presets as well

npm install --save-dev babel-cli
npm install babel-preset-es2015 --save-dev

We will create a symbolic for babel executables located in node_modules/babel-cli/bin directory to our working directory.

Ex :

ln -s ./node_modules/babel-cli/bin/babel-node.js babel-node

Coding with ES6

This is a simple es6 code sample, create file recursion_es6.js and put below content inside it.

let catagories = [
{ id: "animal", "parent": null },
{ id: "mammel", "parent": "animal" },
{ id: "dog", "parent": "mammel" },
{ id: "cat", "parent": "mammel" },
{ id: "pug", "parent": "dog" },
{ id: "german shepard", "parent": "dog" },
{ id: "persian", "parent": "cat" },
{ id: "russian", "parent": "cat" }];

let makeTree = (catagories, parent) => {

let node = {};

catagories
.filter(elem => elem.parent === parent)
.forEach(elem => node[elem.id] = makeTree(catagories, elem.id));

return node;
};

console.log(JSON.stringify(makeTree(catagories, null), null, 2));

Then use babel-node to output your program

./babel-node recursion_es6.js

Happy Babeling…