Use ES6++ Today
ES-WAT ?
• “ECMAScript Language Specification, Edition 6”
• ECMAScript is the official name of JavaScript due to Sun’s (at the time) Java trademark.
• “TC-39” = ECMA Technical Committee 39. Responsible for evolving JavaScript.
TC-39 1999-2008
2009+ ES-Harmony
https://github.com/tc39/ecma262
ES6 aka ES2015• block scoping
• destructuring
• default parameter values
• rest parameters
• spread
• modules
• standard modules
• object literals
• classes
• symbols
• proper tail calls
• iterators
• generators
• array comprehensions
• arrow functions
• weak map
• weak map
• maps and sets
• proxies
• reflection
• Number and Math improvements
• regexp improvements
• String improvements
• Function improvements
ES7 aka ES2016• async functions
• async generators
• exponentiation (**) operator
• typed objects
• class decorators
• object rest properties
• object spread properties
• bind (::) operator
• parallel JavaScript
• destructuring in comprehensions
• generator comprehensions
• Object Observe
• Object.getOwnPropertyDescriptors
• class properties
• Array includes
• Object.entries
• Object.values
• ES8 / ES2017
• Macros; e.g. Sweet.js http://sweetjs.org
• SIMD Parallel Instructions: http://blog.aventine.se/2012/01/22/simd.html
Using Future JavaScript Today
https://babeljs.io
Babel + CLI$ npm install -g babel
compile single file: babel src.es --out-file compiled.js
compile directory: babel src --out-dir lib
watch for changes: add source maps: —-watch --source-maps
Babel + Gulp$ npm install —save-dev gulp-babel
gulpfile.js
var babel = require('gulp-babel');
gulp.task('default', function() { return gulp.src('src/**/*.es') .pipe(babel()) .pipe(gulp.dest('dist')); });
• http://flowtype.org
• OS X: brew install flow
• Other: Download the ZIP.
http://www.typescriptlang.org
Install: $ npm install -g
typescript
Compile: $ tsc src.ts
class Greeter { constructor(public greeting: string) { } greet() { return "<h1>" + this.greeting + "</h1>"; } }; var greeter = new Greeter("Hello, world!"); var str = greeter.greet(); document.body.innerHTML = str;
More ES* Tools
https://github.com/addyosmani/es6-tools
http://kangax.github.io/compat-table/es6
Block Scope
var list = document.getElementById("list");
for (let i = 1; i <= 5; i++) { var item = document.createElement("LI"); item.appendChild(document.createTextNode("Item " + i));
item.onclick = function (ev) { console.log("Item " + i + " is clicked."); }; list.appendChild(item); }
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Default Argumentsfunction singularAutoPlural(singular, plural = singular+"s", rallyingCry = plural + " ATTACK!!!") { return [singular, plural, rallyingCry ]; }
//["Gecko","Geckos", "Geckos ATTACK!!!"] singularAutoPlural(“Gecko”);
//["Fox","Foxes", "Foxes ATTACK!!!"] singularAutoPlural("Fox","Foxes");
//["Deer", "Deer", "Deer ... change."] singularAutoPlural("Deer", "Deer", "Deer peaceably and respectfully petition the government for positive change.")
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
Rest Arguments// Before rest parameters, the following could be found: function fn(a, b){ var args = Array.prototype.slice.call(arguments, fn.length);
// ... }
// to be equivalent of
function fn(a, b, ...args) {
}
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
Template Strings// before template strings console.log(“No\n” + “multiline\n” + “strings”);
// now the equivalent of console.log(`In ES6, you can have true multiline strings`);
Template String Interpolation
// Interpolate expressions into a // template string var name = 'AkJS';
console.log(`Welcome to ${name}`); // = “Welcome to AkJS”
console.log(`The year is ${new Date().getUTCFullYear()}`); // = “The year is 2015”
Tagged Template Stringsfunction tag(strings, ...values) { console.log(strings[0]); // = "Strings come " console.log(strings[1]); // = “.\n Expressions come " console.log(values[0]); // = "first" console.log(values[1]); // = “last" console.log(strings.raw[0]); // = “Strings come first.\\n Expressions come last”
return "The manipulated string"; }
var strs = "first"; var exprs = "last"
tag`Strings come ${strs}.\n Expressions come ${exprs}` // = "The manipulated string"
Tagged Template Stringsfunction SaferHTML(templateData, ...values) { var s = templateData[0]; for (let i = 1; i < values.length; i++) { let arg = String(values[i]);
// Escape special characters in the substitution. s += arg.replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">");
// Don't escape special characters in the template. s += templateData[i]; } return s; }
var message = SaferHTML`<p>${message.sender} has sent you a message.</p>`;
Source: https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/
Modules//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); }
//------ main.js ------ import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5
Source: http://www.2ality.com/2014/09/es6-modules-final.html
Symbolsvar sym1 = Symbol(); var sym2 = Symbol("foo"); var sym3 = Symbol("foo");
sym2.toString(); // Symbol(foo)
sym2 === sym3; // false
var obj = {};
obj[sym2] = "2" obj[sym3] = "3"
More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
Symbolsvar sym = new Symbol(); // TypeError
var sym4 = Symbol.for("foo"); // create a new global symbol var sym5 = Symbol.for("foo"); // retrieve the already created symbol
sym4 === sym5; // true
Symbol.for("co.movio.foo"); // use namespaces to avoid global symbol name clashes
Generatorsfunction* idMaker(){ var index = 0; while(index < 3) yield index++; }
var gen = idMaker();
console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // undefined
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
Iteratorsfor (let n of idMaker()) { print(n); }
function* idMaker(){ var index = 0; while(index < 3) yield index++; }
Destructuring Arraysvar foo = ["one", "two", "three"];
// without destructuring var one = foo[0]; var two = foo[1]; var three = foo[2];
// with destructuring var [one, two, three] = foo;
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Destructuring Objectsvar o = {p: 42, q: true}; var {p, q} = o;
console.log(p); // 42 console.log(q); // true
// Assign new variable names var {p: foo, q: bar} = o;
console.log(foo); // 42 console.log(bar); // true
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Destructuring Argumentsfunction drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) { console.log(size, cords, radius); // do some chart drawing }
drawES6Chart({ cords: { x: 18, y: 30 }, radius: 30 });
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Destructuring Nested Arrays / Objects
var metadata = { title: "Scratchpad", translations: [ { locale: "de", localization_tags: [ ], last_edit: "2014-04-14T08:43:37", url: "/de/docs/Tools/Scratchpad", title: "JavaScript-Umgebung" } ], url: "/en-US/docs/Tools/Scratchpad" };
var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
console.log(englishTitle); // "Scratchpad" console.log(localeTitle); // "JavaScript-Umgebung"
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Destructuring Iteratorsvar people = [ { name: "Mike Smith", family: { mother: "Jane Smith", father: "Harry Smith", sister: "Samantha Smith" }, age: 35 }, { name: "Tom Jones", family: { mother: "Norah Jones", father: "Richard Jones", brother: "Howard Jones" }, age: 25 } ];
for (let {name: n, family: { father: f } } of people) { console.log("Name: " + n + ", Father: " + f); }
// "Name: Mike Smith, Father: Harry Smith" // "Name: Tom Jones, Father: Richard Jones
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Spreadvar parts = ['shoulder', 'knees']; var lyrics = ['head', ...parts, 'and', 'toes']; // = ['head', 'shoulder', 'knees', 'and', 'toes']
let [a, b, ...tail] = [1, 2, 3, 4, 5]; // a = 1, b = 2, tail = [3, 4, 5]
[...idMaker()]; // = [0, 1, 2]
More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
More: http://www.2ality.com/2015/04/numbers-math-es6.html