ES6 and BEYOND

Post on 16-Feb-2017

117 views 0 download

Transcript of ES6 and BEYOND

ES6 Beyon

d!& Beyond

!

Brian Patterson

What and WhyECMAScript 2015(ES6) is next level JavaScript

Clearer, more concise code

Browsers are currently implementing it

You can use it now with Babel.js

Works well with React.js

Forecast

Major Features Let, Const, and Arrow Functions

Classes

Default, Rest, and Spread

Iterators, Generators, & For…Of

Destructuring

Template Strings

Collections

Let, Const and Arrow

Functions(The Green Arrow)

Let

Introduces block scoping into JavaScript

You can usually replace var with it but be careful with existing code.

You can use them instead of IIFE’s to preserve your namespace.

Block Scopingfunction foo() { { console.log(hello); //error, the variable is not defined //code within curly braces is a "block" //this is only available within this block let hello = 1234; } console.log(hello); //output: Error, hello is not defined for (let i = 0; i < 10; i++) { //the variable ‘i’ is only available within the for block } console.log(i); //output: Error, i is not defined}

ConstConstants are immutable variables.

Assigning a new value to it will cause an error

Careful: You can change the properties of an object, as long as you don’t reassign the object itself

Immutable {const foo = 1;foo = 2; //error: cannot change the value of a constant}{const obj = { hello: 'world' };obj.hello = 'galaxy'; //no error!}{const obj = { hello: 'world' };obj = { hello: 'galaxy' }; //error}{const obj = { hello: 'world' };Object.freeze(obj);obj.hello = 'galaxy'; //this will now cause an error}

Arrow Functions

Functions that use the scope of their parent

More concise

No more need for self=this

The problem var myObject = { param: 123, method: function(){ alert( this.param ); }, method2: function(){ setTimeout(function(){ alert( this.param ); },100); }} // method2 alerts undefined

Current Solutionvar myObject = { param: 123, method: function(){ alert( this.param ); }, method2: function(){ var self = this; setTimeout(function(){ alert( self.param ); },100); }}

With Arrow Functions

var myObject = { param: 123, method: function(){ alert( this.param ); }, method2: function(){ setTimeout(() =>{ alert( this.param ) },100); }}

Template Strings(Superman)

Template Strings

String interpolation instead of String concatenation

Multi-line strings

Tagged template strings

String Interpolation

let thing = ‘World’;let greeting = `Hello, ${thing}!`console.log(greeting); // Hello, World!

thing = ‘You’console.log(greeting); // Hello, You!

Multiline Stringsconsole.log(`In West Philiadelphia,

born and raised on the playground is where I spent most of my days`);

Tagged Template Strings

function tag(templates, …substitutions){// templates = [‘Hello ‘, ‘ ‘, ‘!’]// …substitutions = firstName, lastName

console.log(templates[0]); //Helloconsole.log(substitutions[0]); //John}

let firstName = ‘John’let lastName = ‘Smith’tag`Hello ${firstName} ${lastName}!`

Classes and Inheritance

(Batman/Alfred)

Classes and Inheritance

Syntactic sugar for prototypal inheritance

Constructor functions

The Super Keyword

Subclassing with extends

Constructor Functions

function Person(name) { this.name = name;} Person.prototype.describe = function(){ return 'Person called '+this.name;}

Class Syntactic Sugar

class Person { constructor(name) { this.name = name; } describe() { return 'Person called '+this.name; }}

Old way to do inheritance

function Employee(name, title) { Person.call(this, name); // super(name) this.title = title;}Employee.prototype = Object.create(Person.prototype);Employee.prototype.constructor = Employee;Employee.prototype.describe = function () { return Person.prototype.describe.call(this) // super.describe() + ' (' + this.title + ')';};

Subclassing with Extendsclass Employee extends Person {

constructor(name, title) { super(name); this.title = title; } describe() { return super.describe() + ' (' + this.title + ')'; }}

Collections(Fantastic Four)

Collections

Maps

Sets

WeakMaps

WeakSets

MapsMaps are like objects, except you can have objects as keys

Because they are separate, you can use Maps as key value stores without worrying about all the baggage objects bring

There’s no efficient way to see how many properties an object has

Implements Iterable

Mapsvar colorObject = {color: ‘blue’};var myMap = new Map;myMap.set(‘petsAllowed’, ‘for a fee’);myMap.set(colorObject, 4);myMap.get(colorObject); // 4myMap.has(‘petsAllowed’); //truemyMap.size // 2;myMap.delete(colorObject);myMap[Symbol.iterator](); //returns an iteratormyMap.clear();

SetsSets are like arrays except they only contain unique values

Optimized for membership testing

Sets are not indexed

Implements Iterable

Setsvar mySet = new Set;mySet.add(4); //[4]mySet.add(‘hello’); // [4, ‘hello’]mySet.add(4); // [4, ‘hello’]mySet.size; // 2 mySet.has(‘hello’); //truemySet.delete(‘4’) //[‘hello’]mySet[Symbol.iterator](); //returns an iteratormySet.clear();

WeakMapsMaps whose keys must be objects onlyDoes not implement iterable, so you can’t get a list of its contentsOtherwise has all of the map methodsThis is all so that your keys can be garbage collected. Because they are objects, and if there are no other references to them, they can be cleaned up

WeakSetsSets of only objectsDoes not implement iterable, so you can’t get a list of its contentsOtherwise has all of the set methodsThis is all so that your items can be garbage collected. Because they are objects, and if there are no other references to them, they can be cleaned up

Default, Rest, and Spread(Spiderman)

Default, Rest, and Spread

All function parameter tools

Default allows you to set a variable default in the function declaration

Rest allows you to take one or more arguments into an array parameter

Spread is the reverse. It lets you destructure an array argument into the parameter variables

Default

function f(x, y=12) { // y is 12 if not passed // (or passed as undefined) return x + y;}f(3) == 15

Rest

function f(x, ...y) { // y is an Array return x * y.length;}f(3, "hello", true) == 6

Spread

function f(x, y, z) { return x + y + z;}// Pass each element of // array as argumentf(...[1,2,3]) == 6

Destructuring(The Incredible Hulk)

Destructuring

Allows you to assign variables from Arrays

You can skip over elements

Using rest with destructuring

Useful for variable swapping

Destructuring

var first = someArray[0];var second = someArray[1];var third = someArray[2];

var [first, second, third] = someArray;

Skipping elements

var [,,third] = ["foo", "bar", "baz"];console.log(third);// "baz"

Using Rest

var [head, ...tail] = [1, 2, 3, 4];console.log(tail);// [2, 3, 4]

Swappingvar a = 3;var b = 6;var temp; var x = 2; var y = 4;temp = a; //or [x,y] = [y,x]a = b;b = temp;

Iterators, Generators,

For..Of(The Green Lantern)

IteratorsAn iterator is a way for a consumer to pull values from a producer one value at a time.

ES6 has had all collections implement iterable

collection[Symbol.iterator]();

Provides a next() method

Returns an object that looks like this {value: 4, done: false}

Iteration and For..ofvar iterable = [4,6,1];iterable.next(); //{value:4, done: false}iterable.next(); //{value:6, done: false}iterable.next(); //{value:1, done: true}iterable.next(); //{done: true}

var iterable2 = [2,7,4];for(num of iterable2) { console.log(num);}

GeneratorsExtends Iterators and allows you to create them easier

Yield keyword allows for functions that ‘return’ multiple times

Can allow for infinite values

Can receive values

Generatorsfunction* getNumbers() { yield 5; yield 32; yield 8;}

var generator = getNumbers();console.log(generator.next()); // {value: 5, done: false}console.log(generator.next()); // {value: 32, done: false}console.log(generator.next());// {value: 8, done: true}

Infinite Generatorsfunction* getFibonnacci() { var a = 0; var b = 1; yield a; while(true){ [a, b] = [b, a+b]; yield b; }}

var fibonnacci = getFibonnacci();console.log(fibonnacci.next().value)// 0console.log(fibonnacci.next().value)// 1console.log(fibonnacci.next().value)// 1console.log(fibonnacci.next().value)// 2console.log(fibonnacci.next().value)// 3console.log(fibonnacci.next().value)// 5

Yield can take valuesfunction* fillList() {

let list = [];while(list.length < 3) {

list.push(yield list)}return list;

}var myList = fillList();myList.next(); //{"value":[],"done":false}myList.next(5); //{“value”: [5],“done”:false}myList.next(2); //{“value”: [5,2],“done”:true}myList.next(4); //{“done”:true}

Useful Links

http://jsoverson.github.io/es6repl/https://babeljs.io/https://www.youtube.com/watch?v=DqMFX91ToLwhttp://exploringjs.com/es6/

Questions?