JavaScript ES6

23
Welcoming JavaScript ES6 Top 10 reasons why you should be using ES6, number 7 will bring you tears of joy! (Click Here) @leojh

Transcript of JavaScript ES6

Welcoming JavaScript ES6

Top 10 reasons why you should be using ES6, number 7 will bring you tears of joy!

(Click Here)

@leojh

● I work at Third Wave● We are right here at Cendyn Spaces● We build custom business software● We’re doing a lot of JavaScript development● We’re AGILE● We’re here if you need us!● http://thirdwave.it

What is ES6?

● New ECMA standard bringing modern features and cleaner syntax to JavaScript

● Scheduled for official release later in 2015● Mozilla Firefox leading in browser

adoptability● Standard mostly completed● You can begin using it TODAY!

class IntArrayAction{ constructor(ints) { this.ints = ints; } doSomethingOnInts(action) { for (var i of this.ints) { action(i); } }}

var instance = new IntArrayAction([1,2,3,4,5]);instance.doSomethingOnInts((i) => console.log(i));

class IntArrayAction{ constructor(ints) { this.ints = ints; } doSomethingOnInts(action) { for (var i of this.ints) { action(i); } }}

var instance = new IntArrayAction([1,2,3,4,5]);instance.doSomethingOnInts((i) => console.log(i));

class keyword

constructor keyword

iteratorlambda

Some of the Features

ClassesIteratorsLambdasModulesString InterpolationUnicode

Set & Map TypesParameter defaultsLots of Syntax Sugar…And much more

Classes

Structure code in classes instead of object literals or “function objects”Inheritance through extends keyword and call parent members through super(...) Include class members through static keyword (like in C#)

Classesclass SkinnedMesh extends THREE.Mesh {

constructor(geometry, materials) {

super(geometry, materials);

this.idMatrix = SkinnedMesh.defaultMatrix();

this.bones = [];

this.boneMatrices = [];

//...

}

update(camera) {

//...

super.update();

}

static defaultMatrix() {

return new THREE.Matrix4();

}

}

String Interpolation

● Declare using ` (backtick) operator● Lets you put statements inside of stringsvar name = ‘Slim Shady’

var greeting = `Hi, my name is: ${name}!`

● Lets you create multi-line string literalsvar multiLine = `Line 1Line 2`

String Interpolation// Basic literal string creation

`In JavaScript "\n" is a line-feed.`

// Multiline strings

`In JavaScript this is

not legal.`

// Interpolate variable bindings

var name = "Bob", time = "today";

`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction

GET`http://foo.org/bar?a=${a}&b=${b}

Content-Type: application/json

X-Credentials: ${credentials}

{ "foo": ${foo},

"bar": ${bar}}`(myOnReadyStateChangeHandler);

Sets & Maps Types

● A real Map/Dictionary type (finally!)○ Will map a key to a value

● Provides Weak Implementations○ To map object keys to values ○ The contents may be garbage collected if the object

keys are removed from memory

Sets & Map Types// Sets

var s = new Set();

s.add("hello").add("goodbye").add("hello");

s.size === 2;

s.has("hello") === true;

// Maps

var m = new Map();

m.set("hello", 42);

m.set(s, 34);

m.get(s) == 34;

// Weak Maps

var wm = new WeakMap();

wm.set(s, { extra: 42 });

wm.size === undefined

// Weak Sets

var ws = new WeakSet();

ws.add({ data: 42 });

// Because the added object has no other references, it will not be held in the set

Iterators

● Will let you create iterable types like IEnumerable (C#) or Iterable (Java)

● For Each Loops now available (finally!)○ If you are using for..in to iterate arrays, you’re doing

it wrong!

Iteratorslet fibonacci = {

[Symbol.iterator]() {

let pre = 0, cur = 1;

return {

next() {

[pre, cur] = [cur, pre + cur];

return { done: false, value: cur }

}

}

}

}

for (var n of fibonacci) {

// truncate the sequence at 1000

if (n > 1000)

break;

console.log(n);

}

=> (lambdas λ and functions)

● Shorthand for function()● Similar syntax to C#

○ No parentheses for single argument○ No return keyword necessary for single statement

● Will keep reference to outer this for you○ No need to: var self = this;

● Closure

=> (lambdas and functions)// Expression bodies

var odds = evens.map(v => v + 1);

var nums = evens.map((v, i) => v + i);

// Statement bodies

nums.forEach(v => {

if (v % 5 === 0)

fives.push(v);

});

// Lexical this

var bob = {

_name: "Bob",

_friends: [],

printFriends() {

this._friends.forEach(f =>

console.log(this._name + " knows " + f));

}

}

Let Block Scope

● New keyword let for creating block scope● You should probably stop using var and use

let instead (do as I say, not as I do)● var = function scope

let = block scope● BONUS: We have a const keyword

(finally!)

Modules

● Arguably the most important feature● A legitimate way to make code reusable

(finally!) ● Export a module/library● Import the module/library when needed● Transpiles to CommonJS or RequireJS● Provides Static Analysis for dependencies

Modules// lib/math.js

export function sum(x, y) {

return x + y;

}

export var pi = 3.141593;

// app.js

import * as math from "lib/math";

alert("2π = " + math.sum(math.pi, math.pi));

HOW DO I USE IT!?

Learn ES6 in 24 hours!

● Best ES6 resource byfar is babel.js (https://babeljs.io)

● It is currently the leading ES6 transpiler

● Contains a lot of great training material● Has a live ES6 editor● Definitely visit babel.js

Begin using ES6 today!

If you’re using:● ember-cli - start typing ES6 code● react-js - use react-tools● AngularJS - looks complicated, but then again you’re

using Angular so you’re used to it● node - use babel-node tool● Plain old javascript: use broccoli-js

Thank you!@leojh