12/4/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
}); 

http://codepen.io/

Due Preferred: Before you leave

  • 2 HTML elements
    • button
    • div
  • Add a click event to the button to perform the following:
    • Generate a random whole number
    • Build a multiline string interpolated template with the random number.
    • Output the template into the div.
  • Use let and const instead of var
  • Challenge: Don't use jQuery
  • Challenge: Make it less than 15 lines of JavaScript.
  • Hint:Look at Chrome's console for errors.

Optional Practice

Fork this CodePen and convert the array method callbacks into arrow functions.

Pen

>