ES6 Features

A Brief Introduction to some new ECMAScript 6 features

Arrow Functions

Arrow functions provide a shorthand for writing functions using => . Unlike functions, arrows share the same lexical this as their surrounding code.

//ES5
var multiplyByTwo = function(num) {
return num * 2;
};
//ES6
var multiplyByTwo = num => num * 2;

Classes

Classes are mostly syntactic sugar. They provide the same prototypical inheritance of old, with a much cleaner and convenient syntax. Classes support super calls, instance and static methods and constructors.

//ES5
var Person = function(first, last) {
this.first = first;
this.last = last;
};
Person.prototype.personMethod = function() {
// ...
};
var Employee = function(first, last, position) {
Person.call(this, first, last);
this.position = position;
};
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.employeeMethod = function() {
// ...
};
//ES6
class Person {
constructor(first, middle, last) {
this.first = first;
this.middle = middle;
this.last = last;
}
personMethod() {
// ...
}
}
class Employee extends Person {
constructor(first, middle, last, position) {
super(first, middle, last);
this.position = position;
}

employeeMethod() {
// ...
}
}

Let & Const

let replaces var. const is used when variables won’t be reassigned.

//var vs let
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}

function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
//const
const MY_NUM = 26;
MY_NUM = 3; // ERROR

Template Strings — String Interpolation

More syntactic sugar, but for strings!

//ES5
let first = "Mean", middle = "Joe", last = "Green";
console.log("My name is " + first + " " + middle + " " + last + ".");
//ES6
let first = "Mean", middle = "Joe", last = 'Green';
console.log(`My name is ${first} ${middle} ${last}.`);

This is only a brief introduction to a major update to the language. For full specifications please see ES6 standard.