ES6 Hackathon
Do or Die in 30 minutes
Based on:
● https://github.com/ga-wdi-lessons/es6-teach-yourself
Resources:
● https://jsfiddle.net/
● https://www.typescriptlang.org/play/index.html
● http://es6-features.org/
Scopes &
Destructuring
1. Block Scope
2. Modules
3. Destructuring
Introducing: Block Scope
ES5:
function(){
global_var = “do not do this”;
for(var i=0; i<10;i++) {
var local_var = “ok”;
}
document.write(local_var);
}
document.write(global_var);
Output:
“ok”
“do not do this”;
ES6:
function(){
global_var = “do not do this”;
for(var i=0; i<10;i++) {
let local_var = “ok”;
}
document.write(local_var);
}
document.write(global_var);
Output:
ERROR local_var is not defined
“do not do this”;
ES5 has only global scope
and functional scope. The
new “let” operator gives
us the new block scope
feature.
Block scopes are defined
by their parent { }
brackets
Destructuring (like Python)
ES5:
// extract values to semantic variable names
var arrayOne = ['hello', 'there', 'bob'];
var greeting = { greet: 'hello', where: 'there',
name: 'bob' };
var hello = arrayOne[0];
var there = arrayOne[1];
var bob = arrayOne[2];
var greet = greeting.greet;
var where = greeting.where;
var name = greeting.name;
document.write(hello, greet);
ES6:
var arrayOne = ['hello', 'there', 'bob'];
var greeting = { greet: 'hello', where: 'there',
name: 'bob' };
var [hello, there, bob] = arrayOne;
var {greet, where, name} = greeting;
document.write(hello, greet)
Modules (finally!)
/libs/math.js:
export function square(x) {
return x * x;
}
/main.js
import * from ‘./libs/math’;
// Better:
import {square} from ‘./libs/math’;
document.write(square(4));
Finally the missing import
feature for JS! Import
syntax lets us
automatically resolve at
build time what methods
are used, and which aren’t;
for smaller js downloads.
This also improves our
encapsulation and code
hiding.
Destructuring (like Python)
ES5:
// swap two values
var a = 1;
var b = 3;
var temp;
temp = a;
a = b;
b = temp;
console.log(a); // 3
console.log(b); // 1
ES6:
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
Destructuring (like Python)
ES5:
// returning a “tuple” from a function
function f() {
return ["https", "pictures.com",
"xyz/abc", {query: "monkeys",
Limit:10}];
}
var _a = f();
var protocol = _a[0];
var domain = _a[1];
var path = _a[2];
var _b = _a[3];
var query = _b.query;
var limit = _b.limit;
ES6:
function f() {
return ["https", "pictures.com",
"xyz/abc", {query: "monkeys",
Limit:10}];
}
var [protocol, domain, path, {query, limit}] = f();
Code Challenge
https://goo.gl/53Bx2Q
Using Destructuring and
Block Scope print (and calculate)
the deals list.
(Imports don’t work in JSFiddle)
ES6 Functions
1. Arrow Functions
2. Default Parameters
3. Shortening properties and
methods
Arrow Functions
ES5
function writeMessage(txt) {
var that = this;
this.msg = txt;
setTimeout(function () {
return document.write(that.msg);
}, 10);
}
ES6
function writeMessage(txt) {
this.msg = txt;
setTimeout(() => document.write(this.msg), 10);
}
Arrow functions allow us to type
less code, but they also let us
maintain the current scope!
(“lexical this”)
Default Method Params
WARNING:
Unlike Python, where method
defaults are assigned by reference.
Mutable types are not
recommended.
In ES6 defaults are passed by value,
and are safe to use.
ES6
function append(value, array = []) {
array.push(value);
return array;
}
append(1); //[1]
append(2); //[2], not [1, 2]
Object Method Shorthand
ES5
var dog = {
bark: function() {
},
layDown: function () {
}
}
ES6
var dog = {
bark() {},
layDown() {}
}
Object Properties Shorthand
ES5
function createCar(make, model, color) {
var car = {
type: "car",
make: make,
model: model
};
Car[model + ” “ + color] = 2016;
return car;
}
ES6
function createCar(make, model, color) {
return {
type: "car",
make,
model,
[model + “ “ + color]: 2016
};
}
Code Challenge
Update your last challenge
Update your previous challenge
using Arrow Functions, Default
Parameters, and Object Shorthand.
ES6 Classes
1. New Classes Syntax
2. Static
3. Constructors
4. Getters/Setters
Introducing: Classes
Import {Polygon} from “shapes”;
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor
super(length, length);
this.name = 'Square';
}
get_area() {
return this.height * this.width;
}
}
Note: In derived classes,
super() must be called before
you can use 'this'. Leaving this
out will cause a reference
error.
Classes have static methods
class StaticMethodCall {
static staticMethod() {
return 'Static method has been called';
}
static anotherStaticMethod() {
return this.staticMethod() + ' from another static method';
}
}
StaticMethodCall.staticMethod();
// 'Static method has been called'
Classes have get & set
Import {Polygon} from “shapes”;
class Square extends Polygon {
constructor(length) { … }
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
You can use this class like
this:
var sq = Square(10);
console.log(sq.area); // 100
sq.area = 5;
console.log(sq.area); // 25
Code Challenge
https://goo.gl/oMefgW
TDD style, satisfy the assert
statements, and make the
TreeNumber class work.
Use getters & setters, and recurse
the object tree to know the correct
sums for children and parents in the
structure.
New Features
1. Template Literals
2. String Methods
3. Spread
4. Yield / Generators
5. Sets, Arrays
6. Promises
7. Internationalization
Template Strings
ES5
var a = 5;
var b = 10;
console.log("nFifteen is " + (a + b) +
" andnnot " + (2 * a + b) +
".");
// "Fifteen is 15 and
// not 20."
ES6
var a = 5;
var b = 10;
console.log(
`nFifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."
Things to note:
● Back-Tick quotes
● Multi-line
● ${} embedded
● Tagged template literals
(not shown)
New in String:
1. str.startsWith(searchString[, position])
2. str.endsWith(searchString[, position])
3. str.includes(searchString[, position])
4. str.repeat(count)
a. 'abc'.repeat(2); // 'abcabc'
5. str.normalize([form]) // converts to unicode
International Formatting
var l10nEN = new Intl.NumberFormat("en-US")
var l10nDE = new Intl.NumberFormat("de-DE")
l10nEN.format(1234567.89) === "1,234,567.89"
l10nDE.format(1234567.89) === "1.234.567,89"
var l10nUSD = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
var l10nGBP = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" })
var l10nEUR = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" })
l10nUSD.format(100200300.40) === "$100,200,300.40"
l10nGBP.format(100200300.40) === "£100,200,300.40"
l10nEUR.format(100200300.40) === "100.200.300,40 €"
var l10nEN = new Intl.DateTimeFormat("en-US")
var l10nDE = new Intl.DateTimeFormat("de-DE")
l10nEN.format(new Date("2015-01-02")) === "1/2/2015"
l10nDE.format(new Date("2015-01-02")) === "2.1.2015"
Code Challenge
(first deal example)
Return to our first code challenge.
Improve the outputs using
internationalization and
template strings.
Spread...
ES5
var parts = ['shoulders', 'knees'];
var lyrics = ['head'];
lyrics.concat(parts);
lyrics = lyrics.concat(['and', 'toes']);
// ["head", "shoulders", "knees", "and", "toes"]
ES6
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']);
// ["head", "shoulders", "knees", "and", "toes"]
“...Rest” Params
ES5
function f (x, y) {
var a = Array.prototype.slice.call(arguments,
2);
return (x + y) * a.length;
};
f(1, 2, "hello", true, 7); // == 9
ES6
function f (x, y, ...a) {
return (x + y) * a.length
}
f(1, 2, "hello", true, 7); // == 9
Things to note:
Works a lot like *args in python.
Yield Generators
ES5
function fibonacci(max) {
var prev = 0
var curr = 1
var temp = 0
var i = 0
var out = []
for (; prev < max; i++) {
out.push(prev)
temp = prev
prev = curr
curr = temp + curr
}
return out
}
console.log(fibonacci(10))
// [0,1,1,2,3,5,8,13,21,34]
ES6
function* fibonacci(n) {
const infinite = !n && n !== 0;
let current = 0;
let next = 1;
while (infinite || n--) {
yield current;
[current, next] = [next, current + next];
}
}
for (let f of fibonacci(10)) {
console.log(f);
}
// 0 1 1 2 3 5 8 13 21 34
Sets
ES5
var s = {};
s["hello"] = true;
s["goodbye"] = true;
s["hello"] = true;
var s_keys = Object.keys(s);
console.log(s_keys);
// [“goodbye”, “hello”]
ES6
let s = new Set()
s.add("hello").add("goodbye").add("hello");
console.log(s)
// [“hello”, “goodbye”]
Things to note:
● “add” not “append”
● Maintains insertion
order
Code Challenge
https://goo.gl/U3H0W6
Update the getRandomeUnique()
function to be a Generator that
returns a random number between
0-100, but never the same number
twice.
New in Array:
1. for (let value of iterable) {}
2. list.forEach(callback);
3. Array.from([Set, Map, etc..])
4. [1, 2, 3].fill(4); // [4, 4, 4]
5. [...].find(callback); // returns value
6. [...].findIndex(callback); // returns index
7. [...].entries(); // returns an iterator of the array values
Native Promises
var p = new Promise(function(resolve, reject) {
if (/* condition */) {
resolve(/* value */); // fulfilled successfully
}
else {
reject(/* reason */); // error, rejected
}
});
p.then((value) => console.log(“success”, value),
(reason) => console.log(“failure”, reason));
p.catch((err) => console.log("error: ", err.message));
Don’t get confused:
Angular Promises have a
slightly different syntax to
Native Promises. Both solve
the same problem, and in very
similar ways.
Es6 hackathon

Es6 hackathon

  • 1.
    ES6 Hackathon Do orDie in 30 minutes
  • 2.
    Based on: ● https://github.com/ga-wdi-lessons/es6-teach-yourself Resources: ●https://jsfiddle.net/ ● https://www.typescriptlang.org/play/index.html ● http://es6-features.org/
  • 3.
    Scopes & Destructuring 1. BlockScope 2. Modules 3. Destructuring
  • 4.
    Introducing: Block Scope ES5: function(){ global_var= “do not do this”; for(var i=0; i<10;i++) { var local_var = “ok”; } document.write(local_var); } document.write(global_var); Output: “ok” “do not do this”; ES6: function(){ global_var = “do not do this”; for(var i=0; i<10;i++) { let local_var = “ok”; } document.write(local_var); } document.write(global_var); Output: ERROR local_var is not defined “do not do this”; ES5 has only global scope and functional scope. The new “let” operator gives us the new block scope feature. Block scopes are defined by their parent { } brackets
  • 5.
    Destructuring (like Python) ES5: //extract values to semantic variable names var arrayOne = ['hello', 'there', 'bob']; var greeting = { greet: 'hello', where: 'there', name: 'bob' }; var hello = arrayOne[0]; var there = arrayOne[1]; var bob = arrayOne[2]; var greet = greeting.greet; var where = greeting.where; var name = greeting.name; document.write(hello, greet); ES6: var arrayOne = ['hello', 'there', 'bob']; var greeting = { greet: 'hello', where: 'there', name: 'bob' }; var [hello, there, bob] = arrayOne; var {greet, where, name} = greeting; document.write(hello, greet)
  • 6.
    Modules (finally!) /libs/math.js: export functionsquare(x) { return x * x; } /main.js import * from ‘./libs/math’; // Better: import {square} from ‘./libs/math’; document.write(square(4)); Finally the missing import feature for JS! Import syntax lets us automatically resolve at build time what methods are used, and which aren’t; for smaller js downloads. This also improves our encapsulation and code hiding.
  • 7.
    Destructuring (like Python) ES5: //swap two values var a = 1; var b = 3; var temp; temp = a; a = b; b = temp; console.log(a); // 3 console.log(b); // 1 ES6: var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1
  • 8.
    Destructuring (like Python) ES5: //returning a “tuple” from a function function f() { return ["https", "pictures.com", "xyz/abc", {query: "monkeys", Limit:10}]; } var _a = f(); var protocol = _a[0]; var domain = _a[1]; var path = _a[2]; var _b = _a[3]; var query = _b.query; var limit = _b.limit; ES6: function f() { return ["https", "pictures.com", "xyz/abc", {query: "monkeys", Limit:10}]; } var [protocol, domain, path, {query, limit}] = f();
  • 9.
    Code Challenge https://goo.gl/53Bx2Q Using Destructuringand Block Scope print (and calculate) the deals list. (Imports don’t work in JSFiddle)
  • 10.
    ES6 Functions 1. ArrowFunctions 2. Default Parameters 3. Shortening properties and methods
  • 11.
    Arrow Functions ES5 function writeMessage(txt){ var that = this; this.msg = txt; setTimeout(function () { return document.write(that.msg); }, 10); } ES6 function writeMessage(txt) { this.msg = txt; setTimeout(() => document.write(this.msg), 10); } Arrow functions allow us to type less code, but they also let us maintain the current scope! (“lexical this”)
  • 12.
    Default Method Params WARNING: UnlikePython, where method defaults are assigned by reference. Mutable types are not recommended. In ES6 defaults are passed by value, and are safe to use. ES6 function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], not [1, 2]
  • 13.
    Object Method Shorthand ES5 vardog = { bark: function() { }, layDown: function () { } } ES6 var dog = { bark() {}, layDown() {} }
  • 14.
    Object Properties Shorthand ES5 functioncreateCar(make, model, color) { var car = { type: "car", make: make, model: model }; Car[model + ” “ + color] = 2016; return car; } ES6 function createCar(make, model, color) { return { type: "car", make, model, [model + “ “ + color]: 2016 }; }
  • 15.
    Code Challenge Update yourlast challenge Update your previous challenge using Arrow Functions, Default Parameters, and Object Shorthand.
  • 16.
    ES6 Classes 1. NewClasses Syntax 2. Static 3. Constructors 4. Getters/Setters
  • 17.
    Introducing: Classes Import {Polygon}from “shapes”; class Square extends Polygon { constructor(length) { // Here, it calls the parent class' constructor super(length, length); this.name = 'Square'; } get_area() { return this.height * this.width; } } Note: In derived classes, super() must be called before you can use 'this'. Leaving this out will cause a reference error.
  • 18.
    Classes have staticmethods class StaticMethodCall { static staticMethod() { return 'Static method has been called'; } static anotherStaticMethod() { return this.staticMethod() + ' from another static method'; } } StaticMethodCall.staticMethod(); // 'Static method has been called'
  • 19.
    Classes have get& set Import {Polygon} from “shapes”; class Square extends Polygon { constructor(length) { … } get area() { return this.height * this.width; } set area(value) { this.area = value; } } You can use this class like this: var sq = Square(10); console.log(sq.area); // 100 sq.area = 5; console.log(sq.area); // 25
  • 20.
    Code Challenge https://goo.gl/oMefgW TDD style,satisfy the assert statements, and make the TreeNumber class work. Use getters & setters, and recurse the object tree to know the correct sums for children and parents in the structure.
  • 21.
    New Features 1. TemplateLiterals 2. String Methods 3. Spread 4. Yield / Generators 5. Sets, Arrays 6. Promises 7. Internationalization
  • 22.
    Template Strings ES5 var a= 5; var b = 10; console.log("nFifteen is " + (a + b) + " andnnot " + (2 * a + b) + "."); // "Fifteen is 15 and // not 20." ES6 var a = 5; var b = 10; console.log( `nFifteen is ${a + b} and not ${2 * a + b}.`); // "Fifteen is 15 and // not 20." Things to note: ● Back-Tick quotes ● Multi-line ● ${} embedded ● Tagged template literals (not shown)
  • 23.
    New in String: 1.str.startsWith(searchString[, position]) 2. str.endsWith(searchString[, position]) 3. str.includes(searchString[, position]) 4. str.repeat(count) a. 'abc'.repeat(2); // 'abcabc' 5. str.normalize([form]) // converts to unicode
  • 24.
    International Formatting var l10nEN= new Intl.NumberFormat("en-US") var l10nDE = new Intl.NumberFormat("de-DE") l10nEN.format(1234567.89) === "1,234,567.89" l10nDE.format(1234567.89) === "1.234.567,89" var l10nUSD = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }) var l10nGBP = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" }) var l10nEUR = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }) l10nUSD.format(100200300.40) === "$100,200,300.40" l10nGBP.format(100200300.40) === "£100,200,300.40" l10nEUR.format(100200300.40) === "100.200.300,40 €" var l10nEN = new Intl.DateTimeFormat("en-US") var l10nDE = new Intl.DateTimeFormat("de-DE") l10nEN.format(new Date("2015-01-02")) === "1/2/2015" l10nDE.format(new Date("2015-01-02")) === "2.1.2015"
  • 25.
    Code Challenge (first dealexample) Return to our first code challenge. Improve the outputs using internationalization and template strings.
  • 26.
    Spread... ES5 var parts =['shoulders', 'knees']; var lyrics = ['head']; lyrics.concat(parts); lyrics = lyrics.concat(['and', 'toes']); // ["head", "shoulders", "knees", "and", "toes"] ES6 var parts = ['shoulders', 'knees']; var lyrics = ['head', ...parts, 'and', 'toes']); // ["head", "shoulders", "knees", "and", "toes"]
  • 27.
    “...Rest” Params ES5 function f(x, y) { var a = Array.prototype.slice.call(arguments, 2); return (x + y) * a.length; }; f(1, 2, "hello", true, 7); // == 9 ES6 function f (x, y, ...a) { return (x + y) * a.length } f(1, 2, "hello", true, 7); // == 9 Things to note: Works a lot like *args in python.
  • 28.
    Yield Generators ES5 function fibonacci(max){ var prev = 0 var curr = 1 var temp = 0 var i = 0 var out = [] for (; prev < max; i++) { out.push(prev) temp = prev prev = curr curr = temp + curr } return out } console.log(fibonacci(10)) // [0,1,1,2,3,5,8,13,21,34] ES6 function* fibonacci(n) { const infinite = !n && n !== 0; let current = 0; let next = 1; while (infinite || n--) { yield current; [current, next] = [next, current + next]; } } for (let f of fibonacci(10)) { console.log(f); } // 0 1 1 2 3 5 8 13 21 34
  • 29.
    Sets ES5 var s ={}; s["hello"] = true; s["goodbye"] = true; s["hello"] = true; var s_keys = Object.keys(s); console.log(s_keys); // [“goodbye”, “hello”] ES6 let s = new Set() s.add("hello").add("goodbye").add("hello"); console.log(s) // [“hello”, “goodbye”] Things to note: ● “add” not “append” ● Maintains insertion order
  • 30.
    Code Challenge https://goo.gl/U3H0W6 Update thegetRandomeUnique() function to be a Generator that returns a random number between 0-100, but never the same number twice.
  • 31.
    New in Array: 1.for (let value of iterable) {} 2. list.forEach(callback); 3. Array.from([Set, Map, etc..]) 4. [1, 2, 3].fill(4); // [4, 4, 4] 5. [...].find(callback); // returns value 6. [...].findIndex(callback); // returns index 7. [...].entries(); // returns an iterator of the array values
  • 32.
    Native Promises var p= new Promise(function(resolve, reject) { if (/* condition */) { resolve(/* value */); // fulfilled successfully } else { reject(/* reason */); // error, rejected } }); p.then((value) => console.log(“success”, value), (reason) => console.log(“failure”, reason)); p.catch((err) => console.log("error: ", err.message)); Don’t get confused: Angular Promises have a slightly different syntax to Native Promises. Both solve the same problem, and in very similar ways.