SlideShare uma empresa Scribd logo
1 de 52
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?

Mais conteúdo relacionado

Mais procurados

ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015qmmr
 
The Macronomicon
The MacronomiconThe Macronomicon
The MacronomiconMike Fogus
 
あたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるあたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるKazuya Numata
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2Zaar Hai
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기JangHyuk You
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubyJason Yeo Jie Shun
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of RubyTom Crinson
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift OverviewKaz Yoshikawa
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6garux
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQLCarlos Hernando
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVMjwausle
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.jsPierre Spring
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 

Mais procurados (20)

ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
あたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるあたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみる
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQL
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVM
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.js
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 

Destaque

Risk &amp; Volatility
Risk &amp; VolatilityRisk &amp; Volatility
Risk &amp; VolatilityGreg Ferguson
 
Sistema de gestion de calidad
Sistema de gestion de calidadSistema de gestion de calidad
Sistema de gestion de calidadsaldivarfes
 
Temas examen de grado Derecho Procesal - Cristian Ureta Diaz
Temas examen de grado Derecho Procesal - Cristian Ureta DiazTemas examen de grado Derecho Procesal - Cristian Ureta Diaz
Temas examen de grado Derecho Procesal - Cristian Ureta Diazcristianuretadiaz
 
Why It Sucks Getting O
Why  It  Sucks  Getting  OWhy  It  Sucks  Getting  O
Why It Sucks Getting Obasketball9229
 
Entretien eustache 06-10-2006
Entretien eustache 06-10-2006Entretien eustache 06-10-2006
Entretien eustache 06-10-2006Elsa von Licy
 
Por qué fracasan las pymes (1)
Por qué fracasan las pymes (1)Por qué fracasan las pymes (1)
Por qué fracasan las pymes (1)Ariana Tellez
 
Derecho Procesal Civil - Disposiciones Comunes a Todo Procedimiento
Derecho Procesal Civil - Disposiciones Comunes a Todo ProcedimientoDerecho Procesal Civil - Disposiciones Comunes a Todo Procedimiento
Derecho Procesal Civil - Disposiciones Comunes a Todo ProcedimientoCamilo Bernheim
 
ingeniería ferroviaria
ingeniería ferroviariaingeniería ferroviaria
ingeniería ferroviaria357895123
 
English Article
English ArticleEnglish Article
English ArticleJerome124
 
Delitos tributarios en nicaragua
Delitos tributarios en nicaraguaDelitos tributarios en nicaragua
Delitos tributarios en nicaraguaJorge L Garcia O
 
Tomo II, sentencias tributarias administrativas 2007 2014
Tomo II, sentencias tributarias administrativas 2007 2014Tomo II, sentencias tributarias administrativas 2007 2014
Tomo II, sentencias tributarias administrativas 2007 2014Jorge L Garcia O
 
UGent Research Projects on Linked Data in Architecture and Construction
UGent Research Projects on Linked Data in Architecture and ConstructionUGent Research Projects on Linked Data in Architecture and Construction
UGent Research Projects on Linked Data in Architecture and ConstructionPieter Pauwels
 
Traumatisé, stressé, résistant
Traumatisé, stressé, résistantTraumatisé, stressé, résistant
Traumatisé, stressé, résistantPatrice Machabee
 

Destaque (19)

Risk &amp; Volatility
Risk &amp; VolatilityRisk &amp; Volatility
Risk &amp; Volatility
 
Sistema de gestion de calidad
Sistema de gestion de calidadSistema de gestion de calidad
Sistema de gestion de calidad
 
Temas examen de grado Derecho Procesal - Cristian Ureta Diaz
Temas examen de grado Derecho Procesal - Cristian Ureta DiazTemas examen de grado Derecho Procesal - Cristian Ureta Diaz
Temas examen de grado Derecho Procesal - Cristian Ureta Diaz
 
Why It Sucks Getting O
Why  It  Sucks  Getting  OWhy  It  Sucks  Getting  O
Why It Sucks Getting O
 
Entretien eustache 06-10-2006
Entretien eustache 06-10-2006Entretien eustache 06-10-2006
Entretien eustache 06-10-2006
 
C2SM26553B
C2SM26553BC2SM26553B
C2SM26553B
 
Por qué fracasan las pymes (1)
Por qué fracasan las pymes (1)Por qué fracasan las pymes (1)
Por qué fracasan las pymes (1)
 
Stressberedskab
StressberedskabStressberedskab
Stressberedskab
 
Derecho Procesal Civil - Disposiciones Comunes a Todo Procedimiento
Derecho Procesal Civil - Disposiciones Comunes a Todo ProcedimientoDerecho Procesal Civil - Disposiciones Comunes a Todo Procedimiento
Derecho Procesal Civil - Disposiciones Comunes a Todo Procedimiento
 
ingeniería ferroviaria
ingeniería ferroviariaingeniería ferroviaria
ingeniería ferroviaria
 
English Article
English ArticleEnglish Article
English Article
 
Delitos tributarios en nicaragua
Delitos tributarios en nicaraguaDelitos tributarios en nicaragua
Delitos tributarios en nicaragua
 
Tomo II, sentencias tributarias administrativas 2007 2014
Tomo II, sentencias tributarias administrativas 2007 2014Tomo II, sentencias tributarias administrativas 2007 2014
Tomo II, sentencias tributarias administrativas 2007 2014
 
UGent Research Projects on Linked Data in Architecture and Construction
UGent Research Projects on Linked Data in Architecture and ConstructionUGent Research Projects on Linked Data in Architecture and Construction
UGent Research Projects on Linked Data in Architecture and Construction
 
Traumatisé, stressé, résistant
Traumatisé, stressé, résistantTraumatisé, stressé, résistant
Traumatisé, stressé, résistant
 
Pec idie hva
Pec idie hvaPec idie hva
Pec idie hva
 
18 sucesorio 2 esquemas
18 sucesorio 2 esquemas18 sucesorio 2 esquemas
18 sucesorio 2 esquemas
 
January 2015 Presentation
January 2015 PresentationJanuary 2015 Presentation
January 2015 Presentation
 
Neurofeedback Psyrene
Neurofeedback PsyreneNeurofeedback Psyrene
Neurofeedback Psyrene
 

Semelhante a ES6 and BEYOND

A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General IntroductionThomas Johnston
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2Toni Kolev
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyondFrancis Johny
 

Semelhante a ES6 and BEYOND (20)

A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Js hacks
Js hacksJs hacks
Js hacks
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
JavaFXScript
JavaFXScriptJavaFXScript
JavaFXScript
 
Javascript
JavascriptJavascript
Javascript
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Groovy
GroovyGroovy
Groovy
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 

ES6 and BEYOND

  • 2. 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
  • 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 Arrow Functions (The Green Arrow)
  • 6. 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.
  • 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 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
  • 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 that use 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 var myObject = { param: 123, method: function(){ alert( this.param ); }, method2: function(){ setTimeout(() =>{ alert( this.param ) },100); } }
  • 15. Template Strings String interpolation instead 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 West Philiadelphia, 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}!`
  • 20. Classes and Inheritance Syntactic sugar 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 class Person { constructor(name) { this.name = name; } describe() { return 'Person called '+this.name; } }
  • 23. 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 + ')'; };
  • 24. Subclassing with Extends class Employee extends Person { constructor(name, title) { super(name); this.title = title; } describe() { return super.describe() + ' (' + this.title + ')'; } }
  • 27. 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
  • 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 like arrays 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 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
  • 32. 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
  • 33. Default, Rest, and Spread (Spiderman)
  • 34. 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
  • 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
  • 39. Destructuring Allows you to assign 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;
  • 45. 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}
  • 46. 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); }
  • 47. 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
  • 48. 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}
  • 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 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}