ES6 JAVASCRIPT
ECMAScript 6 is a upcoming language update to JavaScript's standards. Its in the final stages of review and will be out Q1 2015.
With a few exceptions, its mainly just sugar syntax that simplifies a lot of the code we already do today or [insert today's favorite framework] supplements.
ES6 classes are syntactical sugar for todays Objects and prototypes.
They offer a nice, cleaner, and clearer syntax for creating/extending objects.
class Animal {
constructor(name) {
this.name = name;
}
}
var animal = new Animal('Abby');
animal.name === 'Abby';
class Animal {
constructor(name) {
this.name = name;
}
talk(msg){
alert(this.name + ' says ' + msg);
}
}
class Panda extends Animal {
talk(msg) {
super(msg);
}
}
var panda = new Panda('Abby');
panda.talk('hi'); //-> 'Abby says hi'
class Animal {
constructor(name) {
this.name = name;
}
talk(msg){
alert(this.name + ' says ' + msg);
}
}
class Panda extends Animal {
talk(msg = 'hi') {
super(msg);
}
}
var panda = new Panda('Abby');
panda.talk(); //-> 'Abby says hi'
panda.talk('moo'); //-> 'Abby says moo'
// ES5
var x = function(x){
return x + 1
};
var x = function(x, y){
return {
x: x,
y: y
};
};
// ES6
let x = (x) => {
return x + 1 };
let x = (x,y) => ({
x: x,
y: y
})
// ES5
var arr = [ "a", "b", "c" ]
arr.forEach(function(r) {
console.log(r);
});
// "a"
// "b"
// "c"
// ES6
var arr = [ "a", "b", "c" ]
for(let el of arr){
console.log(el);
}
// "a"
// "b"
// "c"
// ES5
function count(n){
var res = []
for (var x = 0; x < n; x++) {
res.push(x)
}
return res
}
for (var x of count(5)) {
console.log(x)
}
// ES6
function* count(){
for (var x = 0; true; x++) {
yield x
}
}
for (var x of count()) {
console.log(x)
}
Package your code for easy injection!
Most small projects, just load the script/css files in the html file.
Taking it a step further some people concat and compile to one file for optimization with things like Gulp and Grunt.
Larger projects are hard to deal with because you typically have:
define(['jquery', 'angular'],
function($, angular){
return $('.zoo').text();
});
var $ = require("jquery");
var angular = require("angular");
import $ from 'jquery';
import angular from 'angular';
// math.js
export function sum(x, y) {
return x + y;
};
export var pi = 3.141593;
// app.js
import {sum, pi} from "math";
alert("2π = " + sum(pi, pi));
// otherapp.js
import * as math from "math";
alert("2π = " + math.sum(math.pi, math.pi));
Transpilers turns ES6+ code into vanilla ES5, so you can use next generation features today.
Gulp and Grunt help to automate the trans-compiling tasks.
gulp.task('es6', function () {
return gulp.src(path.source)
.pipe(sourcemaps.init())
.pipe(to5(compilerOptions))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(path.output))
});
SystemJS inside JSPM is a browser module loader system that supports all module formats including ES6.