impress your friends with ecmascript 2015
TRANSCRIPT
EcmaScript 2015impress your friends at the party
What is es6?
Why es6?
Is it Safe to Us Es6?!?!
https://kangax.github.io/compat-table/es6/
How do we use Es6?
https://github.com/rauschma/webpack-es6-demo
https://github.com/angular-class/NG6-starter
Syntactic SugAr
Es6 Classes
ES6 Classes
• Simple sugar over the the prototype-based OO pattern• A more convenient form makes classes easier to use • Classes support inheritance, super calls, instance and static methods and constructors
class Project { constructor(name) { this.name = name; } start() { return `Project ${this.name} starting`; } } var project = new Project("Website"); project.start(); // "Project Website starting"
Es6 Inheritance
ES6 INheritance
• Inheritance is possible via the prototype• You can inherit from a base class using the extends keyword• You must call super before you can access this in a subclass
class Shape { … toString () { return `Shape(${this.id}) ̀ } } class Rectangle extends Shape { constructor (id, x, y, width, height) { super(id, x, y) … } toString () { return "Rectangle > " + super.toString() } } class Circle extends Shape { constructor (id, x, y, radius) { super(id, x, y) … } toString () { return "Circle > " + super.toString() } }
Es6 Modules
ES6 MODULES
• Language-level support for modules for component definition• Best of both both CommonJS and AMD • Named exports and default exports
//------ lib.js ------export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } //------ main.js ------import { square, diag } from 'lib'; console.log(square(11)); // 121console.log(diag(4, 3)); // 5
//------ main.js ------import * as lib from 'lib'; console.log(lib.square(11)); // 121console.log(lib.diag(4, 3)); // 5
//------ myFunc.js ------export default function () { ... }; //------ main1.js ------import myFunc from 'myFunc'; myFunc();
//------ MyClass.js ------export default class { ... }; //------ main2.js ------import MyClass from 'MyClass'; let inst = new MyClass();
Es6 Block Level Scoping
ES6 MODULES
• Function scope can be tricky!• We can scope variables at a block level using let and const
function printName() { if(true) { var name = "Rafael"; } console.log(name); // Rafael}
function printName() { var name; // variable declaration is hoisted to the top if(true) { name = "Rafael"; } console.log(name); // Rafael}
function printName() { if(true) { let name = "Rafael"; } console.log(name); // ReferenceError: name is not defined}
function printName() { var name = "Hey"; if(true) { let name = "Rafael"; console.log(name); // Rafael } console.log(name); // Hey}
if (true) { // enter new scope, TDZ starts // Uninitialized binding for `tmp` is created tmp = 'abc'; // ReferenceError console.log(tmp); // ReferenceError let tmp; // TDZ ends, `tmp` is initialized with `undefined ̀ console.log(tmp); // undefined tmp = 123; console.log(tmp); // 123}
Es6 Arrow functions
ES6 Arrow Functions
• Arrow function expression aka fat arrow functions are a shorter syntax• Lexically binds the this value• Arrow functions are always anonymous
var numbers = [1,2,3,4,5]; var timesTwo = numbers.map(function (number) { return number * 2; }); console.log(timesTwo); // [2, 4, 6, 8, 10]
var numbers = [1,2,3,4,5]; var timesTwo = numbers.map((number) => number * 2); console.log(timesTwo); // [2, 4, 6, 8, 10]
var numbers = [1,2,3,4,5]; var timesTwo = numbers.map(number => number * 2); console.log(timesTwo); // [2, 4, 6, 8, 10]
function FooCtrl (FooService) { this.foo = 'Hello'; FooService .doSomething(function (response) { this.foo = response; }); }
function FooCtrl (FooService) { this.foo = 'Hello'; FooService .doSomething(function (response) { this.foo = response; }.bind(this)); }
function FooCtrl (FooService) { var that = this; that.foo = 'Hello'; FooService .doSomething(function (response) { that.foo = response; }); }
function FooCtrl (FooService) { this.foo = 'Hello'; FooService .doSomething((response) => { // woo, pretty this.foo = response; }); }
function FooCtrl (FooService) { this.foo = 'Hello'; FooService .doSomething(response => this.foo = response); }
Es6 Template Strings
ES6 Template strings
• Multi-line strings• Expression interpolation• Do not let untrusted users construct template strings!
console.log("string text line 1\n"+ "string text line 2"); // "string text line 1// string text line 2"
console.log(`string text line 1 string text line 2`); // "string text line 1// string text line 2"
var a = 5; var b = 10; console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + "."); // "Fifteen is 15 and// not 20."
var a = 5; var b = 10; console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`); // "Fifteen is 15 and// not 20."
Es6 Object Literals
ES6 Object Literals
• Object literals are extended to be more convenient and more like defining a class• Better property and method declarations
var x = 10; var y = 30; var coordinates = { x: x, y: y}; console.log(coordinates); // { x: 10, y: 30 }
let x = 10; let y = 30; let coordinates = { x, y }; console.log(coordinates); // { x: 10, y: 30 }
let x = 10; let y = 30; let coordinates = { x, y, z: 10, }; console.log(coordinates); // { x: 10, y: 30, z: 10 }
var cart = { _items: [], addItem: function(item) { this._items.push(item); return this; }, toString: function() { return this._items.join(', '); } } cart.addItem('apple') .addItem('orange') .addItem('banana'); console.log(cart.toString()); // apple, orange, banana
var cart = { _items: [], addItem(item) { this._items.push(item); return this; }, toString() { return this._items.join(', '); } } cart.addItem('apple') .addItem('orange') .addItem('banana'); console.log(cart.toString()); // apple, orange, banana
Es6 Array API
ES6 Array API
• Array.from converts array-like objects into arrays • Array.keys, Array.values and Array.entries are handy for iterating over arrays• Array.find returns the first element that the callback returns true •Array.findIndex returns the index of the first element that the callback returns true
// Array-like object (arguments) to Arrayfunction f() { return Array.from(arguments); } f(1, 2, 3); // [1, 2, 3]// Any iterable object...// Setvar s = new Set(["foo", window]); Array.from(s); // ["foo", window]// Mapvar m = new Map([[1, 2], [2, 4], [4, 8]]); Array.from(m); // [[1, 2], [2, 4], [4, 8]]// StringArray.from("foo"); // ["f", "o", "o"]
var arr = ["a", "b", "c"]; var iterator = arr.keys(); console.log(iterator.next()); // { value: 0, done: false }console.log(iterator.next()); // { value: 1, done: false }console.log(iterator.next()); // { value: 2, done: false }console.log(iterator.next()); // { value: undefined, done: true }
var arr = ['w', 'y', 'k', 'o', 'p']; var eArr = arr.values(); console.log(eArr.next().value); // wconsole.log(eArr.next().value); // yconsole.log(eArr.next().value); // kconsole.log(eArr.next().value); // oconsole.log(eArr.next().value); // p
var arr = ['a', 'b', 'c']; var eArr = arr.entries(); console.log(eArr.next().value); // [0, 'a']console.log(eArr.next().value); // [1, 'b']console.log(eArr.next().value); // [2, 'c']
function isPrime(element, index, array) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isPrime)); // undefined, not foundconsole.log([4, 5, 8, 12].find(isPrime)); // 5
function isPrime(element, index, array) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not foundconsole.log([4, 6, 7, 12].findIndex(isPrime)); // 2
Es6 SET
ES6 SET
• Lets you store unique values of any type• You can store primitive values or object references
var mySet = new Set(); mySet.add(1); mySet.add(5); mySet.add("some text"); mySet.has(1); // truemySet.has(3); // false, 3 has not been added to the setmySet.has(5); // truemySet.has(Math.sqrt(25)); // truemySet.has("Some Text".toLowerCase()); // truemySet.size; // 3mySet.delete(5); // removes 5 from the setmySet.has(5); // false, 5 has been removedmySet.size; // 2, we just removed one value
Es6 MAP
ES6 MAP
• Simple key/value map• Any value (object or primitive value) can be used as either a key or a value
var myMap = new Map(); var keyObj = {}, keyFunc = function () {}, keyString = "a string"; // setting the valuesmyMap.set(keyString, "value associated with 'a string'"); myMap.set(keyObj, "value associated with keyObj"); myMap.set(keyFunc, "value associated with keyFunc"); myMap.size; // 3// getting the valuesmyMap.get(keyString); // "value associated with 'a string'"myMap.get(keyObj); // "value associated with keyObj"myMap.get(keyFunc); // "value associated with keyFunc"myMap.get("a string"); // "value associated with 'a string'" // because keyString === 'a string' myMap.get({}); // undefined, because keyObj !== {}myMap.get(function() {}) // undefined, because keyFunc !== function () {}
Es6 Resources
https://leanpub.com/exploring-es6/
http://es6-features.org/
http://es6katas.org/
http://www.es6fiddle.net/ http://es6-features.org/ http://www.2ality.com/ https://github.com/lukehoban/es6features http://codepen.io/bradleyboy/posts/getting-to-know-es6-object-literals http://jamesknelson.com/es6-the-bits-youll-actually-use http://jamesknelson.com/es6-cheatsheet.png
Thank you!