ES6
Beyond!
&
Beyond!
Brian Patterson
What and Why
ECMAScript 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 Scoping
function 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
}
Const
Constants 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 Solution
var 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 Strings
console.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]); //Hello
console.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
Extends
class 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
Maps
Maps 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
Maps
var colorObject = {color: ‘blue’};
var myMap = new Map;
myMap.set(‘petsAllowed’, ‘for a fee’);
myMap.set(colorObject, 4);
myMap.get(colorObject); // 4
myMap.has(‘petsAllowed’); //true
myMap.size // 2;
myMap.delete(colorObject);
myMap[Symbol.iterator](); //returns an iterator
myMap.clear();
Sets
Sets are like arrays except they only contain
unique values
Optimized for membership testing
Sets are not indexed
Implements Iterable
Sets
var mySet = new Set;
mySet.add(4); //[4]
mySet.add(‘hello’); // [4, ‘hello’]
mySet.add(4); // [4, ‘hello’]
mySet.size; // 2
mySet.has(‘hello’); //true
mySet.delete(‘4’) //[‘hello’]
mySet[Symbol.iterator](); //returns an iterator
mySet.clear();
WeakMaps
Maps whose keys must be objects only
Does not implement iterable, so you can’t get a list of its
contents
Otherwise has all of the map methods
This 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
WeakSets
Sets of only objects
Does not implement iterable, so you can’t get a list of its
contents
Otherwise has all of the set methods
This 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 argument
f(...[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]
Swapping
var 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)
Iterators
An 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..of
var 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);
}
Generators
Extends 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
Generators
function* 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 Generators
function* 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)// 0
console.log(fibonnacci.next().value)// 1
console.log(fibonnacci.next().value)// 1
console.log(fibonnacci.next().value)// 2
console.log(fibonnacci.next().value)// 3
console.log(fibonnacci.next().value)// 5
Yield can take values
function* 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=DqMFX91ToLw
http://exploringjs.com/es6/
Questions?

ES6 and BEYOND

  • 1.
  • 2.
    What and Why ECMAScript2015(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
  • 3.
  • 4.
    Major Features Let, Const,and Arrow Functions Classes Default, Rest, and Spread Iterators, Generators, & For…Of Destructuring Template Strings Collections
  • 5.
    Let, Const and ArrowFunctions (The Green Arrow)
  • 6.
    Let Introduces block scopinginto 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.
  • 7.
    Block Scoping function 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 }
  • 8.
    Const Constants are immutablevariables. 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
  • 9.
    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 }
  • 10.
    Arrow Functions Functions thatuse the scope of their parent More concise No more need for self=this
  • 11.
    The problem var myObject= { param: 123, method: function(){ alert( this.param ); }, method2: function(){ setTimeout(function(){ alert( this.param ); },100); } } // method2 alerts undefined
  • 12.
    Current Solution var myObject= { param: 123, method: function(){ alert( this.param ); }, method2: function(){ var self = this; setTimeout(function(){ alert( self.param ); },100); } }
  • 13.
    With Arrow Functions varmyObject = { param: 123, method: function(){ alert( this.param ); }, method2: function(){ setTimeout(() =>{ alert( this.param ) },100); } }
  • 14.
  • 15.
    Template Strings String interpolationinstead of String concatenation Multi-line strings Tagged template strings
  • 16.
    String Interpolation let thing= ‘World’; let greeting = `Hello, ${thing}!` console.log(greeting); // Hello, World! thing = ‘You’ console.log(greeting); // Hello, You!
  • 17.
    Multiline Strings console.log(`In WestPhiliadelphia, born and raised on the playground is where I spent most of my days`);
  • 18.
    Tagged Template Strings function tag(templates,…substitutions){ // templates = [‘Hello ‘, ‘ ‘, ‘!’] // …substitutions = firstName, lastName console.log(templates[0]); //Hello console.log(substitutions[0]); //John } let firstName = ‘John’ let lastName = ‘Smith’ tag`Hello ${firstName} ${lastName}!`
  • 19.
  • 20.
    Classes and Inheritance Syntacticsugar for prototypal inheritance Constructor functions The Super Keyword Subclassing with extends
  • 21.
    Constructor Functions function Person(name){ this.name = name; } Person.prototype.describe = function(){ return 'Person called '+this.name; }
  • 22.
    Class Syntactic Sugar classPerson { constructor(name) { this.name = name; } describe() { return 'Person called '+this.name; } }
  • 23.
    Old way todo 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 + ')'; };
  • 24.
    Subclassing with Extends class Employeeextends Person { constructor(name, title) { super(name); this.title = title; } describe() { return super.describe() + ' (' + this.title + ')'; } }
  • 25.
  • 26.
  • 27.
    Maps Maps are likeobjects, 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
  • 28.
    Maps var colorObject ={color: ‘blue’}; var myMap = new Map; myMap.set(‘petsAllowed’, ‘for a fee’); myMap.set(colorObject, 4); myMap.get(colorObject); // 4 myMap.has(‘petsAllowed’); //true myMap.size // 2; myMap.delete(colorObject); myMap[Symbol.iterator](); //returns an iterator myMap.clear();
  • 29.
    Sets Sets are likearrays except they only contain unique values Optimized for membership testing Sets are not indexed Implements Iterable
  • 30.
    Sets var mySet =new Set; mySet.add(4); //[4] mySet.add(‘hello’); // [4, ‘hello’] mySet.add(4); // [4, ‘hello’] mySet.size; // 2 mySet.has(‘hello’); //true mySet.delete(‘4’) //[‘hello’] mySet[Symbol.iterator](); //returns an iterator mySet.clear();
  • 31.
    WeakMaps Maps whose keysmust be objects only Does not implement iterable, so you can’t get a list of its contents Otherwise has all of the map methods This 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
  • 32.
    WeakSets Sets of onlyobjects Does not implement iterable, so you can’t get a list of its contents Otherwise has all of the set methods This 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
  • 33.
    Default, Rest, andSpread (Spiderman)
  • 34.
    Default, Rest, and Spread Allfunction 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
  • 35.
    Default function f(x, y=12){ // y is 12 if not passed // (or passed as undefined) return x + y; } f(3) == 15
  • 36.
    Rest function f(x, ...y){ // y is an Array return x * y.length; } f(3, "hello", true) == 6
  • 37.
    Spread function f(x, y,z) { return x + y + z; } // Pass each element of // array as argument f(...[1,2,3]) == 6
  • 38.
  • 39.
    Destructuring Allows you toassign variables from Arrays You can skip over elements Using rest with destructuring Useful for variable swapping
  • 40.
    Destructuring var first =someArray[0]; var second = someArray[1]; var third = someArray[2]; var [first, second, third] = someArray;
  • 41.
    Skipping elements var [,,third]= ["foo", "bar", "baz"]; console.log(third); // "baz"
  • 42.
    Using Rest var [head,...tail] = [1, 2, 3, 4]; console.log(tail); // [2, 3, 4]
  • 43.
    Swapping var a =3; var b = 6; var temp; var x = 2; var y = 4; temp = a; //or [x,y] = [y,x] a = b; b = temp;
  • 44.
  • 45.
    Iterators An iterator isa 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}
  • 46.
    Iteration and For..of variterable = [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); }
  • 47.
    Generators Extends Iterators andallows you to create them easier Yield keyword allows for functions that ‘return’ multiple times Can allow for infinite values Can receive values
  • 48.
    Generators function* getNumbers() { yield5; 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}
  • 49.
    Infinite Generators function* 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)// 0 console.log(fibonnacci.next().value)// 1 console.log(fibonnacci.next().value)// 1 console.log(fibonnacci.next().value)// 2 console.log(fibonnacci.next().value)// 3 console.log(fibonnacci.next().value)// 5
  • 50.
    Yield can takevalues function* 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}
  • 51.
  • 52.