ES2015 Introduction

Learning the Details

The Mozilla In-Depth Series might be the best place to learn the right way to do ES2015.

Dr. Alex R. also has a paid book and free version on LeanPub called Exploring ES6.

Destructuring

for variable assignment

Use this to extract data out of an array or object. The destructoring operator is used on the left side of the equal sign. You must know the order of your input array or names of the keys in the input object to be able to use destructuring.

The destructing operator ... will always be inside [square brackets] for arrays or inside {curly braces} for objects.

[a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]

for passing anonymously (spread)

The spread operator can be used when calling a function:
let greeting = formatGreeting(...user);

Notice the spread operator is not wrapped in curly braces or square brackets.

It also works when constructing an array literal:
let trucks = ['f-150', 'ram'];
let cars = ['acura', 'buick', 'cadillac', ...trucks];

The Spread operator works similarly to destructuring by expanding iterable into individual pieces.

Rest operator

Rest is the opposite of Spread. It will condense multiple values into an array or object.

Default Function Argument Values

function (color = 'red') {
	console.log(color); //red
}

Arrow Functions

Arrow functions (also call fat-arrow functions) are always anonymous. Classic anonymous functions are typically written similar to this:

function foo() {
	setTimeout(function() {
		console.log(this.id);
	}, 1000);
}
foo.call({id: 123}); //returns an error because "this" does not have an id property

Rewriting that as an arrow function makes it look like:

function foo() {
	setTimeout( () => {
		console.log(this.id);
	}, 1000);
}
foo.call({id: 123}); //displays 123

The reason it works with arrow functions the this property is not created or set. So, when this.id was referenced Javascript couldn’t find this. It then does what it always does when a variable is not found; it looks looks up the chain to see if the parent has this defined.

Classes

Example:

class Polygon {
	constructor(width, height) {
		this.width = width;
		this.height = height;
	}
	area() {
		return this.width * this.height;
	}
	static isLandscape(width, height) {
		if (width > height) {
			return true;
		} else {
			return false;
		}
	}
}

let myRectangle = new Polygon(15, 4);
console.log(Polygon.isLandscape(6,3)); //true

Notice: