Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ES6 at PayPal

ES6 at PayPal

An internal talk given at PayPal about how to take advantage of ES6 in our Kraken/Express apps.

Jamund Ferguson

December 16, 2015
Tweet

More Decks by Jamund Ferguson

Other Decks in Technology

Transcript

  1. Why are you here? » Already familiar with ES6? »

    Using ES6 every day » Just learning node? » New to JavaScript? » ???
  2. EcamScript 3 Example var states = { "CA": "California", "WA":

    "Washington" }; for (var state in states) { if (states.hasOwnProperty(state)) { console.log(state); // "CA", "WA" } }
  3. EcmaScript 5 » Finalized in late 2009 » Includes things

    like Object.keys(), Object.create() and Array.forEach() » As well as standardizing JSON » A lot of cool HTML5 features came out around this time including CSS3 and much of what is known as HTML5 (localStorage, Canvas, etc.)
  4. EcamScript 5 Example var states = { "CA": "California", "WA":

    "Washington" }; Object.keys(states).forEach(function(state) { console.log(state); // "CA", "WA" });
  5. JavaScript Today let states = { "CA": "California", "WA": "Washington"

    }; Object.keys(states) .forEach(state => console.log(state)); // "CA", "WA"
  6. Default Parameters (ES5) $.fn.makeJump = function(height) { height = height

    || 50; $(this).css({ top: -1 * height, position: "relative" }); }; // make the chickens jump $(".chickens").makeJump();
  7. Default Parameters (ES6) $.fn.makeJump = function(height = 50) { $(this).css({

    top: -1 * height, position: "relative" }); }; // make the chickens jump $(".chickens").makeJump();
  8. Anytime you need to concatenate strings together consider using template

    literals instead. var name = first + ' ' + last; magically becomes: var name = `${first} ${last}`;
  9. Here's another handy use for template literals: var x =

    ` I have a wonderful block of text here and I want it to span many many many lines `;
  10. Destructuring Arrays (ES5) // node example var file = fs.readFileSync('myFile.txt',

    'utf8'); var contents = file.split('\n'); var line1 = contents[0]; var line2 = contents[1]; var line3 = contents[2]; var line5 = contents[4];
  11. Destructuring Arrays (ES6) // node example var file = fs.readFileSync('myFile.txt',

    'utf8'); var contents = file.split('\n'); var [line1,line2,line3,,line5] = contents;
  12. Arrow Functions (ES5) var people = [ { name: "suzie",

    age: 26 }, { name: "joe", age 32 }, { name: "sally", age: 5 } ]; // var greetings = people.filter(function(person) { // return person.age > 18; // }) // .map(function(person) { // return "Hello " + person.name; // });
  13. Arrow Functions (ES5) var people = [ { name: "suzie",

    age: 26 }, { name: "joe", age 32 }, { name: "sally", age: 5 } ]; var greetings = people.filter(function(person) { return person.age > 18; }) // .map(function(person) { // return "Hello " + person.name; // });
  14. Arrow Functions (ES5) var people = [ { name: "suzie",

    age: 26 }, { name: "joe", age 32 }, { name: "sally", age: 5 } ]; var greetings = people.filter(function(person) { return person.age > 18; }).map(function(person) { return "Hello " + person.name; });
  15. Arrow Functions (ES6) var people = [ { name: "suzie",

    age: 26 }, { name: "joe", age 32 }, { name: "sally", age: 5 } ]; var greetings = people .filter(person => person.age > 18) .map(person => "Hello " + person.name);
  16. Arrow Functions » No need to return in most cases

    » Parens generally required around params » Multi-line arrow funcs need curly brackets » To self-execute wrap in parens first
  17. Arrow Function Examples var sayHi = () => console.log("hi"); var

    getName = (person) => person.name; var getName = person => person.name; var longThing = (one, two) => { return one * two; }; (x => console.log(x))("hey"); // self executing
  18. Advanced Example (ES5) function getUser(id) { var id = id

    || USER_ID; $.get('/people/' + id, function(person) { var age = person.age; var names = person.name.split(' '); var first = names[0]; console.log(first + ' is ' + age + '.'); }); }
  19. Advanced Example (ES5) function getUser(id) { var id = id

    || USER_ID; // $.get('/people/' + id, function(person) { // var age = person.age; // var names = person.name.split(' '); // var first = names[0]; // console.log(first + ' is ' + age + '.'); // }); }
  20. Default Params (ES6) function getUser(id = USER_ID) { // $.get('/people/'

    + id, function(person) { // var age = person.age; // var names = person.name.split(' '); // var first = names[0]; // console.log(first + ' is ' + age + '.'); // }); }
  21. Advanced Example function getUser(id = USER_ID) { $.get('/people/' + id,

    function(person) { var age = person.age; var names = person.name.split(' '); var first = names[0]; console.log(first + ' is ' + age + '.'); }); }
  22. Destructuring Objects (ES6) function getUser(id = USER_ID) { $.get('/people/' +

    id, function(person) { var { name, age } = person; // var [first, last] = name.split(' '); // console.log(first + ' is ' + age + '.'); }); }
  23. Destructuring Arrays (ES6) function getUser(id = USER_ID) { $.get('/people/' +

    id, function(person) { var { name, age } = person; var [first, last] = name.split(' '); // console.log(first + ' is ' + age + '.'); }); }
  24. Combined Example function getUser(id = USER_ID) { $.get('/people/' + id,

    function(person) { var { name, age } = person; var [first, last] = name.split(' '); console.log(first + ' is ' + age + '.'); }); }
  25. Arrow Functions(ES6) function getUser(id = USER_ID) { $.get('/people/' + id,

    (person) => { var { name, age } = person; var [first, last] = name.split(' '); console.log(first + ' is ' + age + '.'); }); }
  26. Template Literals function getUser(id = USER_ID) { $.get(`/people/${id}`, (person) =>

    { var { name, age } = person; var [first, last] = name.split(' '); console.log(`${first} is ${age}.`); }); }
  27. What are promises? Promises are an alternative way to deal

    with asynchronous code in JavaScript. They are composable and can help simplify error handling in while doing complex asynchronous operations.
  28. There are a lot of promise implementations » Q »

    BlueBird » jQuery Deferred » Deferred.js » Vow » avow » ...
  29. Promise Version $.get(`/people/${id}`).then((person) => { var { name, age }

    = person; var [first, last] = name.split(' '); console.log(`${first} is ${age}.`); });
  30. What happens where there's a problem? $.get(`/people/${id}`).then((person) => { var

    { name, age } = person; var [first, last] = name.split(' '); console.log(`${first} is ${age}.`); }).fail(function() { console.log(`Could not retrieve person ${id}`); });
  31. What if there's a problem inside our code? $.get(`/people/${id}`).then((person) =>

    { var { name, age } = notPerson; // throws a ReferenceError // ... }).fail(function() { console.log(`Could not retrieve person ${id}`); });
  32. What if there's a problem inside our code? $.get(`/people/${id}`).then((person) =>

    { var { name, age } = notPerson; // throws a ReferenceError // ... }).catch(function() { // catch can handle both types of errors console.log(`Could not retrieve person ${id}`); });
  33. Using catch with jQuery today // wrap $.get or $.ajax

    in Promise.resolve function get(url) { return Promise.resolve($.get(url)); } // reference the newly created function get("/my/url") .then(doSomething) .catch(allErrors);
  34. Rest / Spread // create a world with no people

    var world = { people: [] }; // make it easy to populate the world world.populate = function () { for (var i = 0; i < arguments.length; i++) { world.people.push(arguments[i]); } } // add some people to the world world.populate(new Person(“Sally”), new Person(“Joan”));
  35. Rest / Spread // create a world with no people

    var world = { people: [] }; // makes it easier to populate the world world.populate = function (...people) { world.people.push(...people); } // add some people to the world world.populate(new Person(“Sally”), new Person(“Joan”));
  36. ES7 Object Spread // object literal let person = {

    name: "jamund", age: 24 }; // simple and fancy object merging... let me = { age: 32, ...person }
  37. Module Pattern var MY_MODULE = (function($) { var x, y,

    z; return $.doSomething(); }(jQuery));
  38. ES6 Modules import $ from 'jquery'; var x, y, z;

    export default $.doSomething();
  39. ES6 Modules (Examples) // export stuff in one file export

    var age = 32; export function printName() { console.log('Jamund Ferguson'); }; // in another file import { age, printName } from 'my-module'; import * as myThing from 'my-module'; printName(); // Jamund Ferguson console.log(age); // 32
  40. Babel & Kraken Apps Add a .babelrc file: { "presets":

    ["es2015"], "plugins": ["add-module-exports"] }
  41. Babel & Kraken Apps Install some dependencies: npm i --save

    babel-core npm i --save babel-register npm i --save babel-preset-es2015 npm i --save babel-plugin-add-module-exports
  42. Babel & Kraken Apps Add babel-register to your index.js file

    // Add ES6 Support require('babel-register');