12/6/2018

ECMAScript 6 Intro

Documentation

Primary Goals of ES6

Make JavaScript better for writing

  • complex and large applications
  • libraries
  • code generators

Can I use ES6 now?

Yes, if you don't have to support IE11 (b2b apps likely need to support IE11)

If you do need to support IE11, Babel allows for maximum compatibility.

We can use Gulp to compile with Babel

New Variable Declarations

let and const

let

let defines a block level variable. It can help prevent confusion in going through source code.

Prevents errors

See the Pen ES6 - Let by Jon (@Middaugh) on CodePen.

Scoping

See the Pen UA-Let-Scoping by Jon (@Middaugh) on CodePen.

const

const is used to generate variables that do not change.

Using const

See the Pen UA-const by Jon (@Middaugh) on CodePen.

New String Features

We have several new feature inside of strings that are very helpful.

String interpolation

String concatenation is much easier with the new ES6 features. Variables can be injected into strings by using the ` (grave accent) instead of single/double quotes and using the ${x} symbols.

^ interpolation only works within the `` ticks.

Template Strings

See the Pen ES6 - Interpolation by Jon (@Middaugh) on CodePen.

Multiline Strings

You can also use the ` symbol for multi line strings.

Usage

See the Pen ES6 - strings by Jon (@Middaugh) on CodePen.

Arrow Functions

Arrow functions are yet another feature introduced into ES6 that other languages leverage. Arrow functions help remove some confusion of the `this` keyword. It is very helpful, but it isn't always the best fit.

Arrow Function Syntax

Function Expression


    .on('click', function(){
    });
    

Arrow Function


    .on('click', () => {
    });
    

Variations

Shorthand Functions


    function(y){
        var x = 3;
        return x * y; 
    }
   

    (y) => {
        var x = 3;
        return x * y; 
    }
   

Single Line


var rn = function(y){
    return Math.random() * y; 
}
rn();
   

//No curly braces signifies 
//it is returning the calculation.
var rn =  (y) => Math.random() * y; 
n(4); 

   

Even More Examples.

Arrow functions are awesome when used with Arrays.

[].filter((element) => element.isSomething == true); 
[].filter((element) => {
    return element.isActive && element.isInDate
}); 

Questions?

Modules

Module patterns have been built into JavaScript libraries for some time, but they are now available native in the language.

Module are single instances of code designed to be reused throughout an application.

Modules are heavily used in NodeJS and Angular Applications.

Module Exporting


        // /lib/math.js
        export function multiply(x,u){
            return x * u;
        }
        export const pi = 3.14
        

    import {multiply, pi} from 'lib/math';
    console.log(multiply(pi, 4));
    

Module Importing

import {multiply, pi} from 'lib/math';
  • import - All imports occur before any other code
  • {multiply, pi} - Imported objects must be properly exported.
  • from
  • 'lib/math' - Relative path to the file. .js file extension is not required.

Module Execution

  • Modules are Singleton
  • They do not execute until they are imported.
  • Only one instance exists when it's imported.

Making Modules Compatible for the Web

Unfortunately, modules don't natively work in browser, but we can use a tool called Babel to compile our modules into browser compatible JavaScript.


       npm install --save-dev gulp-babel babel-preset-es2015 
        

    const gulp = require('gulp');
    const babel = require('gulp-babel');
 
    gulp.task('default', () => {
        return gulp.src('src/app.js')
            .pipe(babel({
                presets: ['es2015']
            }))
            .pipe(gulp.dest('dist'));
    });
        

JavaScript Classes

Classes provide JavaScript a better opportunity to behave like an Object Oriented Programming Language.

You could make it behave like OOP by enforcing strict patterns.

Caution

This is where this starts getting complicated.

Puns

Class Declaration

You must declare a class before you use it.


class Square{
}
    

Usage


var sq = new Square();
    

Class Structure

  • Constructor
  • Methods

Constructors

A constructor is a specific method used in the initialization of a class.

There can only be one constructor per class.


 class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }
 }
   

var rc = new Rectangle(10, 15);
  

What is an instance of a class?

The class is like a blueprint, an object is an actual instance of the class.

Methods

No code is allowed outside of method. The function keyword is not required.


 class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }

    calcArea(){
        return this.height * this.width;
    }
 }

        var rc = new Rectangle(10, 10);
        console.log(rc.calcArea());
        

Get Methods

Get methods allow you to create dynamic read only properties without requiring the user to call a method.


 class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }

    get area(){
        return this.calcArea();
    }
    calcArea(){ 
        return this.height * this.width;
    }
 }
 

    var rc = new Rectangle(10, 10);
    console.log(rc.area);
        

MDN Documentation

Set Methods


 class Log{
    constructor(){
    this.log = [];
    }
    get logHistory(){
        return this.log; 
    }
    set currentLog(value){
        this.log.push(value);
    }
 }
 

    var lg = new Log();
    lg.currentLog = 'new message';
    console.log(lg.logHistory);
        

    class Person {

        constructor(){}

        get fullName() {
            return this.firstName + ' ' + this.lastName;
        }

        set fullName (name) {
            var words = name.toString().split(' ');
            this.firstName = words[0] || '';
            this.lastName = words[1] || '';
        }

    }

            

Static Methods

Static Methods are methods associated with a class, but are not a part of the instance of the class.

Static Method Example


class Number{
    constructor(n){
        this.num = n;
    }
    increment(){
        this.num++;
    }
    static square(num){
        return num * num;
    }
}
   

var x = new Number(1);
x.increment();
x.square() //error
Number.square(2); //return 4
        
    

Sub Classes

Subclasses extend an existing class. It shares the same methods and properties of it's parent class.

Sub Class Example


class Rectangle {
    constructor(height, width){
        this.name = 'Rectangle';
        this.height = height;
        this.width = width;
    }
  get area(){
    return this.height * this.width;
  }
}


class Square extends Rectangle{
    constructor(length){
        super(length, length);
        this.name = 'Square';
    }
}

var rect = new Rectangle(10, 5);
console.log(rect.name); //Rectangle
console.log(rect.area); //50

var sq = new Square(5);
console.log(sq.name); //Square
console.log(sq.height); //5
console.log(sq.area); //25
        

Before you leave - http://codepen.io/

  • Create a class called Person
  • Its constructor needs to accept and assign the following values
    • First Name
    • Last Name
    • Email Address
  • Add a get method that returns the user's full name.
  • Instantiate 3 users with different first and last names.

Challenge

  • Place all of your users into an array called users
  • Write a function that will accept an array of users and a search phrase
  • In the function, filter and return any users that match the search phrase.

Promises

A promise is the eventual result of an async operation.


let getAccountInfo = new Promise(function(resolve, reject){
let gotData = true;

	if(gotData){
		resolve('User is Jon');
	} else {
		reject('No user info');
	}
});
    

How do we call it?


getAccountInfo.then(function(result){
	console.log(result);
}).catch(function(result){
	console.log(result);
});
    

promise Chaining

Pretend we have three promises we've created. How do we call them sequentially?


getAccountInfo.then(function(result){
	return getUserSecurity(result);
}).then(function(result){
	return getAccessLevels(result);
}).then(function(result){
	console.log(result + " is the result of three calls");
});
    

Promise.all and Promise.raise

Promise.all is used when three calls can be made concurrently instead of sequentially


Promise.all([getAccountInfo(), getUserSecurity(), getAccessLevels()]).then(function(){
	console.log('All done');
});
    

Promise.raise fires as soon as one child finishes


Promise.raise([getAccountInfo(), getUserSecurity(), getAccessLevels()]).then(function(){
	console.log('One is done');
});
    
>