1 of 14

JavaScript ES6 Babel

By Charlie Calvert

URL: http://bit.ly/js-es6-babel

2 of 14

Overview

  • Review of Immediately Invoked Function Expressions
  • ES6 Arrow Functions
  • ES6 Classes
  • Using Babel to Transpile ES6 code into ES5 code
  • Using NPM to install necessary packages and libraries.

3 of 14

Commonly Used JavaScript Engines

4 of 14

Summary

ES6 is term for describing a generation of JavaScript code. ES5 was the previous standard for JavaScript, and it is still very common.

This slide deck shows a simple way to write ES6 code and use a tool called babel to transpile it into ES5. By converting your ES6 code into ES5 code, you get the best of both worlds: You can write ES6 code, but run it on systems that can only handle ES5 syntax.

At this time, however, node can already handle most ES6 code, and production systems usually use a tool called webpack to call babel. As a result the code shown on this deck is usually not used in production systems. Nevertheless, it is important that you understand babel, and that you see what the ES5 equivalent of ES6 code looks like. As a result, this deck has practical applications, and contains code that all modern JavaScript programmers should understand.

5 of 14

Immediately Invoked Function Expressions

The convention is to begin with an open paren to signal that you plan to immediately invoke the function. The call operator at the end of the statement is what actually invokes the function.

(function() {

console.log("Immediately invoke with ES5");

})();

(() => {

console.log("Immediate invocation ES6");

})();

6 of 14

ES5 version of the Array Logger

(function (numbers) {

numbers.forEach(function(number) {

console.log(number);

});

})(['one', 'two', 'three']);

var logger = function logger(numbers) {

numbers.forEach(function (number) {

console.log(number);

});

};

var numbers = ['four', 'five', 'six'];

logger(numbers);

Use ES5 style functions to log the values of an array.

Array.forEach was added in ES5.

The first instance uses the call operator to immediately invoke the function, passing in an array as a parameter.

The second instance assigns an anonymous function to the variable logger. We call the function and pass an array to it.

7 of 14

ES6 Arrow Functions

((numbers) => {

numbers.forEach((number) => {

console.log(number);

})

})(['one', 'two', 'three']);

var logger = (numbers) => {

numbers.forEach((number) => {

console.log(number);

})

};

var numbers = ['four', 'five', 'six'];

logger(numbers);

Two ways to write the same code. Both use arrow functions to print out an array. The first is immediately invoked, while the second is called by name. Save both into a single file called index.js.

8 of 14

Using Babel to Transpile ES6 to ES5

mkdir simple-es6

cd simple-es6

npm init

npm install babel-cli babel-core --save-dev

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

echo '{ "presets": ["es2015"] }' > .babelrc

cp ../work.js . // Copy file into folder

node_modules/.bin/babel work.js -d es5

At this time, the newer versions of node can handle most ES6 syntax. However, there are some browsers that cannot handle ES6 code, and older versions of node cannot compile ES6. If you saved the code from the previous slide into index.js then the code shown above would transpile it into ES5 compatible code. See the next slide.

The last line creates a directory called es5 that contains a copy of index.js that uses ES5 syntax. Run it from inside your new directory.

When you run npm init you will be stepped through a wizard. It should be fairly obvious how to complete the wizard. If you truly can't see what to do, just take the defaults.

9 of 14

Simple Arrow Function

To create an ES6 arrow function, start with the parameter list, then an arrow operator (=>), then the declaration. Curly braces and return are not required.

function addEs5(operanda, operandb) {

return operanda + operandb;

}

const addEs6 = (operanda, operandb) => {

return operanda + operandb;

};

const addConcise = (a, b) => a + b;

console.log(addEs5(2,3));

console.log(addEs6(5, 7));

console.log(addConcise(12, 14));

10 of 14

ES6 Array Logger with Arrow Functions

((numbers) => {

numbers.forEach((number) => {

console.log(number);

});

})(['one', 'two', 'three']);

var logger = (numbers) => {

numbers.forEach((number) => {

console.log(number);

});

};

logger(['four', 'five', 'six']);

Use arrow functions instead of ES5 style functions.

The first instance uses the call operator to immediately invoke the function, passing in an array as a parameter.

The second instance assigns an anonymous function to the variable logger. We call the function and pass an array to it.

11 of 14

ES6 for..of with Arrow Functions

((numbers) => {

for (let number of numbers) {

console.log(number);

}

})(['one', 'two', 'three']);

const loggerForOf = (numbers) => {

for (let number of numbers) {

console.log(number);

}

};

loggerForOf(['four', 'five', 'six']);

Use ES6 for..of instead of ES5 style forEach. Iterate over the iterable properties of an object.

Over-simplification: the members of an array are iterable, the properties of an object are enumerable. We use for..of with arrays, and for..in with objects.

for..in: see next slide.

12 of 14

ES6 for..in with Arrow Functions

const myObject = { first: 'alpha', last: 'omega' };

const loggerForIn = (myObject) => {

for (let property in myObject) {

if (myObject.hasOwnProperty(property)) {

console.log(property);

}

}

};

loggerForIn(myObject);

Use ES6 for..in on an object. It will iterate over the enumerable properties of an object in an undefined order. The built-in properties of an Object or Array have non-enumerable properties. We don't need it here, but we use hasOwnProperty to ensure we get properties only of this object, not inherited properties.

13 of 14

Simple ES6 Class Definition

View the Source

class Person {

constructor(first, last) {

this.first = first;

this.last = last;

}

fullName() {

return this.first + ' ' + this.last;

}

// getLast = () => this.last;

}

var person = new Person('George', 'Washington');

console.log(person.fullName());

14 of 14

Set up .babelrc

Syntax for running Babel

npm init; # Create package.json

npm install babel-cli --save-dev

npm install babel-preset-env --save-dev

npm install --save-dev babel-preset-stage-1

echo '{ "presets": ["env", "stage-1"] }' > .babelrc

./node_modules/.bin/babel work.js -d bundle

node bundle/work.js

Uncomment this method from the previous example:

getLast = () => this.last;