ES6 and BEYOND

52
ES6 Beyond ! & Beyond ! Brian Patterson

Transcript of ES6 and BEYOND

Page 1: ES6 and BEYOND

ES6 Beyon

d!& Beyond

!

Brian Patterson

Page 2: ES6 and BEYOND

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

Page 3: ES6 and BEYOND

Forecast

Page 4: ES6 and BEYOND

Major Features Let, Const, and Arrow Functions

Classes

Default, Rest, and Spread

Iterators, Generators, & For…Of

Destructuring

Template Strings

Collections

Page 5: ES6 and BEYOND

Let, Const and Arrow

Functions(The Green Arrow)

Page 6: ES6 and BEYOND

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.

Page 7: ES6 and BEYOND

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}

Page 8: ES6 and BEYOND

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

Page 9: ES6 and BEYOND

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}

Page 10: ES6 and BEYOND

Arrow Functions

Functions that use the scope of their parent

More concise

No more need for self=this

Page 11: ES6 and BEYOND

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

Page 12: ES6 and BEYOND

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

Page 13: ES6 and BEYOND

With Arrow Functions

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

Page 14: ES6 and BEYOND

Template Strings(Superman)

Page 15: ES6 and BEYOND

Template Strings

String interpolation instead of String concatenation

Multi-line strings

Tagged template strings

Page 16: ES6 and BEYOND

String Interpolation

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

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

Page 17: ES6 and BEYOND

Multiline Stringsconsole.log(`In West Philiadelphia,

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

Page 18: ES6 and BEYOND

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}!`

Page 19: ES6 and BEYOND

Classes and Inheritance

(Batman/Alfred)

Page 20: ES6 and BEYOND

Classes and Inheritance

Syntactic sugar for prototypal inheritance

Constructor functions

The Super Keyword

Subclassing with extends

Page 21: ES6 and BEYOND

Constructor Functions

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

Page 22: ES6 and BEYOND

Class Syntactic Sugar

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

Page 23: ES6 and BEYOND

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 + ')';};

Page 24: ES6 and BEYOND

Subclassing with Extendsclass Employee extends Person {

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

Page 25: ES6 and BEYOND

Collections(Fantastic Four)

Page 26: ES6 and BEYOND

Collections

Maps

Sets

WeakMaps

WeakSets

Page 27: ES6 and BEYOND

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

Page 28: ES6 and BEYOND

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();

Page 29: ES6 and BEYOND

SetsSets are like arrays except they only contain unique values

Optimized for membership testing

Sets are not indexed

Implements Iterable

Page 30: ES6 and BEYOND

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();

Page 31: ES6 and BEYOND

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

Page 32: ES6 and BEYOND

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

Page 33: ES6 and BEYOND

Default, Rest, and Spread(Spiderman)

Page 34: ES6 and BEYOND

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

Page 35: ES6 and BEYOND

Default

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

Page 36: ES6 and BEYOND

Rest

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

Page 37: ES6 and BEYOND

Spread

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

Page 38: ES6 and BEYOND

Destructuring(The Incredible Hulk)

Page 39: ES6 and BEYOND

Destructuring

Allows you to assign variables from Arrays

You can skip over elements

Using rest with destructuring

Useful for variable swapping

Page 40: ES6 and BEYOND

Destructuring

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

var [first, second, third] = someArray;

Page 41: ES6 and BEYOND

Skipping elements

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

Page 42: ES6 and BEYOND

Using Rest

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

Page 43: ES6 and BEYOND

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;

Page 44: ES6 and BEYOND

Iterators, Generators,

For..Of(The Green Lantern)

Page 45: ES6 and BEYOND

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}

Page 46: ES6 and BEYOND

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);}

Page 47: ES6 and BEYOND

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

Page 48: ES6 and BEYOND

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}

Page 49: ES6 and BEYOND

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

Page 50: ES6 and BEYOND

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}

Page 51: ES6 and BEYOND

Useful Links

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

Page 52: ES6 and BEYOND

Questions?