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

Understand ES2015

Understand ES2015

Mark Pedrotti

October 15, 2015
Tweet

More Decks by Mark Pedrotti

Other Decks in Programming

Transcript

  1. So what ES it? ECMAScript. ES2015 (also known as ES6)

    
 is a version of JavaScript 
 published on 17 June 2015.
  2. In Effective JavaScript, 
 David Herman distinguishes • ECMAScript: the

    “ideal language” specified by the Ecma standard • JavaScript: the language 
 as it exists in actual practice
  3. What do you think and feel 
 about change? In

    Web and app technology,
 the rate of change is changing • from infrequent big hunks • to frequent small chunks
  4. For example, • from 10 years, 1999 to 2009,
 between

    ES3 and ES5 • to 12 weeks, June to September,
 between ES2015 and Node.js 4.0
  5. 
 And our information is changing • from books with

    editors and documentation with reviewers • to blog articles with tweets and code repositories with stars
  6. So don’t let change be a problem! Let’s change our

    rate of learning • from occasional upgrades • to continuous integration
  7. Our learning objectives: • Code literacy 
 Understand what you

    read • Code fluency 
 Mean what you write 
 and write what you mean
  8. The robustness principle is parallel to the learning objectives. •

    Liberal in what you receive 
 Understand what you read • Conservative in what you send 
 Mean what you write
  9. 1. let 2. const 3. literal object shortcuts 4. destructuring

    5. import 6. export 7. arrow functions
  10. 1. let is the new var Declare a let variable

    “just in time” because its scope is the rest of the • block • statement where you declare it. Duh!
  11. Color theme: “Skookum autumn” • yellow means strong or emphasis

    • orange is for the ES2015 keyword • red is for corresponding ES5 code
  12. // Example from React Router: matchRoutes.js function matchRouteDeep(basename, route, location,

    callback) { let pattern = route.path || ''; // scope is same as var if (pattern.indexOf('/') !== 0) { // Relative paths build on the parent's path. pattern = basename.replace(/\/*$/, '/') + pattern; } // and so on }
  13. // Example adapted from Redux: slim-redux.js function createStore(reducer, initialState) {

    let state = initialState; // scope is same as var let dispatching = false; // scope is same as var function dispatch(action) { // store.dispatch(action) if (dispatching) { throw new Error('Reducers may not…’); } try { dispatching = true; state = reducer(state, action); } finally { dispatching = false; }
  14. // Return an array in which each coordinate is scaled

    by factor. function scale(factor, point) { let scaled = []; // scope is same as var for (let i = 0, length = point.length; i < length; i += 1) { scaled[i] = factor * point[i]; } // scope of i and length is limited to the for statement return scaled; } //But map provides a functional alternative without let! //return point.map(function (coord) { return factor * coord; });
  15. // Example from Node.js, MongoDB and AngularJS Web Development let

    mongoClient = new MongoClient(…); // scope is similar to var mongoClient.open(function (err, client) { if (err) { console.error(err); } else { let db = client.db(dbName); if (db) { … } } // scope of db is limited to the else block }); //But connect provides a functional alternative without let! MongoClient.connect(…, function (err, db) { … });
  16. If you write functions which have 
 loose coupling and

    tight cohesion, then var was the old let :) Even if function scope is your scope, 
 traditional variable scope matters to traditional software developers…
  17. Server tech Universal Linux Heroku Apache Node.js MySQL GraphQL Perl/PHP/Python

    → JavaScript Remember you heard it here first HeNoGraJa tech stack
  18. Mobile tech Universal C# → JavaScript Java → JavaScript Objective-C

    or Swift → JavaScript + React Native + Relay
  19. Before you replace var with let, 
 find and fix

    existing problems: • 'use strict'; // strict mode • ESLint { "no-undef": 2,
 "block-scoped-var": 2,
 "no-use-before-define": 2,
  20. 1. Learning resources for let: • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Statements/let • https://babeljs.io/docs/learn-es2015/#let-const

    • http://www.2ality.com/2015/02/es6-scoping.html • https://gist.github.com/gaearon/ffd88b0e4f00b22c3159 • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Strict_mode • http://eslint.org
  21. 2. const is the other new var • Assign a

    const variable once. 
 In its declaration. • The scope of a const variable 
 is the same as a let variable.
  22. a. The case of a variable name 
 can answer

    “why is it const?” • UPPERCASE: You can’t reassign it because it can’t change. • otherCase: You don’t reassign it 
 in this program.
  23. // You can’t reassign it: const PI = 22 /

    7; function area(r) {
 return PI * r * r;
 } // Error in strict mode; some engines ignore it in non-strict mode :(
 PI = 3.141592; // You don’t reassign it in this program:
 const areaOfMyCircle = area(7);
  24. b. In Redux, action types 
 are usually string constants.

    • Undo and redo actions 
 while an app is running. • Save logs of actions 
 to rerun an app later.
  25. const ADD_TODO = 'ADD_TODO';
 const COMPLETE_TODO = 'COMPLETE_TODO';
 // action

    objects in Redux: // { // type: ADD_TODO, // text: 'Understand ES2015' // } // { // type: COMPLETE_TODO, // index: 0 // }
  26. c. If the value of a const variable 
 is

    an object or array, 
 properties or items can change. A const variable is immutable. The value is immutable if 
 it is boolean, number, or string.
  27. const action = {}; // You can change properties of

    the object // which was assigned to the const variable. action.type = ADD_TODO; action.text = 'Understand ES2015'; // Error in strict mode: you can’t reassign the const variable.
 action = { type: ADD_TODO, text: 'Understand ES2015' };
  28. a. name and value of a property: 
 Don’t Repeat

    Yourself (DRY) For example, in Redux, 
 a property of an action object 
 often corresponds to 
 an argument of an action creator.
  29. // { // type: ADD_TODO, // text: 'Understand ES2015' //

    } // addTodo('Understand ES2015'); // ES2015 function addTodo(text) { return { type: ADD_TODO, text }; } // action object in Redux // action creator function call // ES5 function addTodo(text) { return { type: ADD_TODO, text: text }; }
  30. // ES2015 const Todo = React.createClass({ render() { // JSX

    is a future topic :) return ( <li>{ … }</li> ); } }); // ES5 var Todo = React.createClass({ render: function () { // JSX is a future topic :) return ( <li>{ … }</li> ); } });
  31. 3. Learning resources for literal object shortcuts: • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Operators/Object_initializer#Property_definitions

    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Operators/Object_initializer#Method_definitions • https://babeljs.io/docs/learn-es2015/#enhanced-object-literals • http://exploringjs.com/es6/ch_oop-besides-classes.html • http://rackt.github.io/redux/docs/basics/Actions.html#action- creators
  32. 4. destructuring With a similar literal notation • you put

    together a structure • you take apart a structure It looks like property name shortcut.
  33. // ES5 or ES2015: put together // with literal object

    notation var action = { type: ADD_TODO, text: 'Understand ES2015' }; // ES5: put together // with dot notation // var action = {}; // action.type = ADD_TODO; // action.text = 'Understand …'; // ES2015: take apart // with destructuring assignment const { type, text } = action; //type === ADD_TODO //text === 'Understand ES2015' // ES5: take apart // with dot notation // var type = action.type; // var text = action.text;
  34. // Create a React element with its props object. const

    todo = {text: 'Understand ES2015', completed: false}; React.createElement(Todo, {todo}); // ES5: {todo: todo} const Todo = React.createClass({ render() { const {todo: {text, completed}} = this.props; // double destruct const className = completed ? 'completed' : 'uncompleted'; // this.props.todo.completed return ( <li className={className}>{text}</li> ); // ES5: this.props.todo.text } });
  35. // ES2015: Destructuring an argument of a Redux reducer function:

    // Given the previous state and an action, return the next state. function reduceTodos(todos, {type, text}) { // ES5: action switch (type) { // ES5: action.type case ADD_TODO: return todos.concat({ text, // ES5: text: action.text completed: false }); default: return todos; } }
  36. // Return an array in which each coordinate is scaled

    by factor. function scale(factor, point) { return point.map(function (coord) { return factor * coord; }); } // ES2015: Destructuring the returned value from a function call: const [x, y, z] = scale(7, [2, 3]); // x === 7 * 2 // y === 7 * 3 // typeof z === 'undefined' /* “fail-soft” like array index */ var scaled = scale(7, [2, 3]); // scaled[0] === 7 * 2 && scaled[1] === 7 * 3 && scaled.length === 2
  37. 5. import is the new require ES2015 module structure is

    static, 
 so JavaScript tools can • optimize access to imports • check references to imports • check types of imports
  38. Write what you mean. To answer, 
 “which kind of

    module dependency?” • static: import • dynamic: require.ensure(…) 
 React Router dynamic routing
 Webpack code splitting
  39. // ES2015 named imports (like destructuring the exports object :)

    import {Router, Route, Link} from 'react-router'; // ES5 CommonJS require // var ReactRouter = require('react-router'); // var Router = ReactRouter.Router; // var Route = ReactRouter.Route; // var Link = ReactRouter.Link;
  40. // ES2015 default imports import React from 'react'; import ReactDOM

    from 'react-dom'; const Todo = React.createClass({ render() { return ( … ); } }); ReactDOM.render(<Todo onclick={onClick} todo={todo} />, node); // ES5 CommonJS require // var React = require('react'); // var ReactDOM = require('react-dom');
  41. // ES2015 default and named imports import React, {createClass} from

    'react'; import {render} from 'react-dom'; const Todo = createClass({ render() { return ( … ); } }); render(<Todo onClick={onClick} todo={todo} />, node); // React.createElement(Todo, {onClick, todo}) // ES5 CommonJS require // var React = require('react'); // var createClass = React.createClass; // var render = require('react-dom').render;
  42. // ES2015 default and named import import React, {Component} from

    'react'; class Todo extends Component { // ES2015 class is a future topic :) render() { const {onClick, todo: {text}} = this.props; return ( <li onClick={onClick}>{text}</li> ); // React.createElement('li', {onClick}, text) } } // ES5 CommonJS require // var React = require('react'); // class Todo extends React.Component { … }
  43. // ES2015 named imports import {createStore, combineReducers} from 'redux'; import

    {filter, todos} from '../reducers'; const store = createStore(combineReducers({ filter, todos })); // var Redux = require('redux'); // var reducers = require('../reducers'); // var store = Redux.createStore(Redux.combineReducers({ // filter: reducers.filter, // todos: reducers.todos // });
  44. // ES2015 named imports import {createStore, combineReducers} from 'redux'; import

    {filter, todos} from '../reducers'; const store = createStore(combineReducers({filter, todos})); // ES2015 namespace import: * represents the named exports object import {createStore, combineReducers} from 'redux'; import * as reducers from '../reducers'; const store = createStore(combineReducers(reducers));
  45. 5. Learning resources for import: • https://babeljs.io/docs/learn-es2015/#modules • http://www.2ality.com/2014/09/es6-modules-final.html •

    https://github.com/rackt/react-router#installation • http://rackt.github.io/redux/docs/basics/Reducers.html#splitting- reducers • http://rackt.github.io/redux/docs/basics/Store.html
  46. 6. export ES2015 modules are stored in files: • one

    module per file • one file per module
  47. // ES2015 default export export default React.createClass({ render() { return

    ( … ); } }); // ES5 CommonJS default export module.exports = React.createClass({ render() { return ( … ); } });
  48. // ES2015 default export of a class export default class

    Todo extends Component { render() { return ( … ); } }
  49. // ES2015 named exports export function diameter(r) { return 2

    * r; } export function area(r) { return Math.PI * r * r; } // ES5 CommonJS exports exports = { diameter: function (r) { return 2 * r; }, area: function (r) { return Math.PI * r * r; } }; // exports.diameter = function … // exports.area = function …
  50. 7. arrow functions, also known as 
 lambda functions Read

    the “fat arrow” operator => 
 as a function with • arguments at the left • return value at the right
  51. a. Less is more clear, 
 especially for a pure

    function: • same inputs => same output • no side effects
  52. // ES2015 arrow functions const diameter = r => 2

    * r; const area = r => Math.PI * r * r; // Parentheses are optional if a function has one argument. // const diameter = (r) => 2 * r; // const area = (r) => Math.PI * r * r; // ES5 functions // var diameter = function (r) { return 2 * r; }; // var area = function (r) { return Math.PI * r * r; }; // function diameter(r) { return 2 * r; } // function area(r) { return Math.PI * r * r; }
  53. // ES2015 export arrow functions from a module export const

    diameter = r => 2 * r; export const area = r => Math.PI * r * r; // ES2015 arrow functions as methods of an object // For example, an ES5 CommonJS exports object exports = { diameter: r => 2 * r, area: r => Math.PI * r * r };
  54. b. Less is more clear, 
 especially if a pure

    function 
 is an argument of a function. 
 For example, 
 an argument of the map function
  55. // Return an array in which each coordinate is scaled

    by factor. // ES2015 arrow function argument of map function function scale(factor, point) { return point.map(coord => factor * coord); } // ES5 function argument of map function function scale(factor, point) { return point.map(function (coord) { return factor * coord; }); }
  56. // Return an array in which each coordinate is scaled

    by factor. // ES2015 arrow function only for argument of map function function scale(factor, point) { return point.map(coord => factor * coord); } // ES2015 arrow functions for scale and argument of map function // Parentheses are required if it has zero or multiple arguments. const scale = (factor, point) => point.map(coord => factor * coord); // Here is a way you might describe the arrow functions: // “Given a factor and a point, return a new point array // in which each coordinate is scaled by factor.”
  57. export default class Todos extends Component { render() { const

    {todos, onClickTodo} = this.props; // ES5: .map(function (todo, index) { return <Todo … />; }) return ( <ul> {todos.map((todo, index) => <Todo todo={todo} key={index} onClick={() => onClickTodo(index)} />)} </ul> ); // ES5: onClick={function () { onClickTodo(index); }} } }
  58. // This just in! React 0.14: A stateless functional component

    // has only an implicit render method with props as its argument. export default ({todos, onClickTodo}) => ( <ul> {todos.map((todo, index) => <Todo todo={todo} key={index} onClick={() => onClickTodo(index)} />)} </ul> ); //render() { // const {todos, onClickTodo} = this.props; // return ( <ul{ … }</ul> ); //}
  59. c. If you define a function 
 without typing function…the

    era of worrying about context is over. The best programmers write code beginners understand. @ryanflorence
  60. // ES2015 arrow function has “lexical this” where it is

    defined. Duh! class ClickableThingy extends Component { handleClick(e) { /* do somethingy */ }, render() { return ( <button onClick={(e) => this.handleClick(e)}>Thingy</button> ); // ES5: function (e) { this.handleClick(e); } // Firefox: TypeError: this is undefined // Chrome: TypeError: cannot read property of undefined } }
  61. 7. Learning resources for arrow functions: • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Functions/Arrow_functions •

    https://babeljs.io/docs/learn-es2015/#arrows-and-lexical-this • http://www.2ality.com/2015/10/methods-vs-callbacks-es6.html • https://facebook.github.io/react/blog/2015/10/07/react- v0.14.html#stateless-functional-components • https://medium.com/@ryanflorence/functions-without-function- bc356ed34a2f
  62. Learning resources about ES2015: • https://developer.mozilla.org/en-US/docs/Web/JavaScript • https://www.webkit.org/blog/4054/es6-in-webkit/ • https://babeljs.io/docs/learn-es2015/

    • http://www.2ality.com/2015/10/es6-feature-lists.html • https://twitter.com/JavaScriptDaily Learning resources about Redux: • https://github.com/rackt/redux • http://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html • http://davidandsuzi.com/writing-a-basic-app-in-redux/ • http://www.jchapron.com/2015/08/14/getting-started-with-redux/