ES6 Essentials

Lecture # 1

ReactJS course for UXD LAB  

Speaker: Ales Tsvil  

12/13/2016

Today

  • ES6 and StyleGuide
  • Babel and it's presets
  • Tooling

Tomorrow

  • ReactJS in details
  • JSX
  • React-router
  • Redux, Redux-react-router
  • Isomorphic React
  • RxJS
  • TSX

ECMAScript 6 (ECMA-262-6)

  • Block-Scoped Variables and Functions, Arrow Functions
  • Extended Parameter Handling and Default Parameter Values
  • Rest Parameter, Spread Operator
  • Template Literals and String Interpolation, Custom Interpolation, Raw String Access
  • Extended Literals, Binary & Octal Literal
  • Better Unicode and RegExp access
  • Enhanced Object Properties, Property Shorthand, Computed Property Names
  • Method Properties and Destructuring Assignment
  • Array Matching, Object Matching, Shorthand Notation, Object Matching, Deep Matching
  • Parameter Context Matching, Fail-Soft Destructuring
  • Modules, Value Export/Import, Default & Wildcard
  • Classes, Class Definition, Class Inheritance, From Expressions
  • Base Class Access, Static Members, Getter/Setter
  • Symbol Type, Global Symbols
  • Iterator & For-Of Operator, Generator Function, Iterator Protocol, Direct Use
  • Generator Matching and Control-Flow, Generator Methods
  • Map/Set & WeakMap/WeakSet, Set Data-Structure, Map Data-Structure
  • Weak-Link Data-Structures and Typed Arrays
  • New Built-In Methods, Object Property Assignment
  • Array Element Finding, String Repeating, String Searching
  • Number Type Checking, Safety Checking, Comparison, Truncation, Sign Determination
  • Promises Usage and Combination
  • Meta-Programming, Proxying, Reflection, Internationalization & Localization, Collation
  • Number Formatting, Currency Formatting, Date/Time Formatting

What we exactly need now?

  • let, const
  • modules
  • class, extends, and other features
  • object literals new features
  • functions default parameters
  • arrow functions
  • destructuring, rest and spread
  • string interpolations and template
  • promise

Block scoped variables

const PI = 3.141593;

PI = 3.14; //Will rise 'Uncaught TypeError: Assignment to constant variable.'

for (let i = 0; i < 10; i++) {
    console.log(i);
}

console.log(i); //Will rise 'Uncaught ReferenceError: i is not defined'

{
    let scoped = 'scoped';
    console.log(scoped);
}
console.log(scoped); //Same as above

let i;
console.log(i); //Temporary dead zone, rise error
i = 1;
let i = 2; //SyntaxError will thrown.

Modules

export { name1, name2, …, nameN };
export { variable1 as name1, variable2 as name2, …, nameN };
export let name1, name2, …, nameN; // also var
export let name1 = …, name2 = …, …, nameN; // also var, const

export default defaultMember;
export default function (…) { … } // also class, function*
export default function defaultMember(…) { … } // also class, function*
export { defaultMember as default, … };

export * from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;

import defaultMember from "module-name";
import * as name from "module-name";
import { name1 } from "module-name";
import { name1 as alias } from "module-name";
import { name1, name2 } from "module-name";
import { name1, name2 as alias2 , [...] } from "module-name";
import defaultMember, { name1 [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name";

Class, methods

class Shape {
    constructor (id, x, y) {
        this.id = id;
        this.move(x, y);
    }
    move (x, y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        return `shape at x: ${this.x} and y: ${this.y}`;
    }
}

Base, extends

class Rectangle extends Shape {
    constructor (id, x, y, width, height) {
        super(id, x, y);
        this.width  = width;
        this.height = height;
    }
    toString() {
        return 'Reactangular ' + super.toString();
    }
}
class Circle extends Shape {
    constructor (id, x, y, radius) {
        super(id, x, y);
        this.radius = radius;
    }
}

Static Methods

class Rectangle extends Shape {
    constructor (id, x, y, width, height) {
        super(id, x, y);
        this.width  = width;
        this.height = height;
    }
    move (x, y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        return `shape at x: ${this.x} and y: ${this.y}`;
    }
    static defaultRectangle () {
        return new Rectangle("default", 0, 0, 100, 100);
    }
}

Object Literal

Object.assign(dst, ...src); // Built in merge function
let obj = { x, y }; // Property shorthands
let obj = {
    foo: "bar",
    [ "baz" + quux() ]: 42
}; // Computed properties
obj = {
    foo (a, b) {
        …
    },
    bar (x, y) {
        …
    },
    *quux (x, y) {
        …
    }
}; // Methods shorhand

Function, =>, Rest, Spread

function f (x, y = 7, z = 42) { // Default parameters
    return x + y + z;
}

nums = evens.map((v, i) => v + i) // Arrow functions
let arrowCb = (a, b) => a + b;
let expB = b => { 
    b += 'updated';
    console.log(b);
};

this.nums.forEach((v) => { // Lexical this
    if (v % 5 === 0) {
        this.fives.push(v);
    }
});

function f (x, y, ...a) { // Rest parameters
    return (x + y) * a.length;
}

var params = [ "hello", true, 7 ]; // Spread operator
var other = [ 1, 2, ...params ]; // [ 1, 2, "hello", true, 7 ]

Destructuring, Object matching

var list = [ 1, 2, 3 ]; // Array matching;
var [ a, , b ] = list;
[ b, a ] = [ a, b ];

var { op, lhs, rhs } = getASTNode(); // Object matching
var { op: a, lhs: { op: b }, rhs: c } = getASTNode(); // Even nested!

function f ([ name, val ]) { // Work for parameters
    console.log(name, val);
}
function g ({ name: n, val: v }) {
    console.log(n, v);
}
f([ "bar", 42 ]);
g({ name: "foo", val:  7 });

var list = [ 7, 42 ]; // Fail soft destructuring
var [ a = 1, b = 2, c = 3, d ] = list;

c == 3, d == undefined;

String features

let name = 'Ales'; // Regular string
let message = `Hello, ${name}, how are you?`; //Template with interpolation

let multiline = `<div class="message-box">
                    <span class="welcome-msg">
                        ${message}
                    </span>
                </div>`;

// String parser selection
fetch `http://example.com/foo?bar=${bar + baz}&quux=${quux}`; 
// Raw string access (backslashes are not interpreted).
String.raw `http://google.com\\n aasdasd`;

Promise

function msgAfterTimeout (msg, who, timeout) {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(`${msg} Hello ${who}!`), timeout);
    });
}
msgAfterTimeout("", "Foo", 100).then((msg) =>
    msgAfterTimeout(msg, "Bar", 200)
).then((msg) => {
    console.log(`done after 300ms:${msg}`)
});

Promise.all([
    fetchPromised("http://backend/foo.txt", 500),
    fetchPromised("http://backend/bar.txt", 500),
    fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
    let [ foo, bar, baz ] = data;
    console.log(`success: foo=${foo} bar=${bar} baz=${baz}`);
}, (err) => {
    console.log(`error: ${err}`);
});

What is it
How to use
Presets

Configuration

Presets

Within special .babelrc file and webpack.config.js

$ npm install --save-dev babel-preset-es2015
$ npm install --save-dev babel-preset-react
$ npm install --save-dev babel-preset-latest
{
  "presets": [
    "es2015",
    "react"
  ]
}

Tooling

Usefull Links

Home Task

   Create OOP data converter module containing class hierarchy with using of some GoF patterns like Adapter. 

   Module has one method - createConverter which supplied with simple object:

 {from: {string}, to: {string}},

based on this object module will return correct converter (perform some checks on object, we can't convert bytes to meters obviously).

Converter object has one method - convert, with single parameter and return converted value as string;

Any questions?

Thank for your attention!

ReactJS Prerequisites

By diodredd

ReactJS Prerequisites

First lecture from course about building apps with ReactJS

  • 840