Ignite es6

Post on 08-Jan-2017

407 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

Transcript

The Future of JavaScript with ES6

Banning the var statement

function loop (array) { for (var index = 0; i < array.length; index++) { /* do stuff */ } console.log(index); // => STILL AVAILABLE??? }

Use let instead

function loop (array) { for (let index = 0; i < array.length; index++) { /* do stuff */ } console.log(index); // Not anymore!!! }

There’s also const

const x = 1; x = 2; // not possible!

const obj = { x: 1 }; obj.x = 2; // possible!

Remember anonymous functions?

[1,2,3,4].map(function(n){ return n * n; });

Hello arrow functions!

[1,2,3,4].map((n) => n * n);

Also default parameters are in town!

function (x, y = 2) { return x + y);

Consider this

Getting the rest

function addPlayersToTeam (team /*, players*/) { var players = arguments.slice(1); for (var i = 0; args.length; i++) { team.addPlayer(args[i]); } }

Thank you rest parameter

function addPlayersToTeam (team, …rest) { rest.forEach((player) => team.addPlayer(player)); }

Destructing your object

var {a, c} = {a: 1, b: 2, c: 3}

console.log(a); // logs 1

Destructing arrays

var foo = [“one”, “two”, “three" ] var one = foo[0]; var [one, two] = foo;

Easier Recursive

function sum ([x, …rest]) { if (x) return x + sum(rest); else return 0;

}

console.log(sum([1,2,3]));

Fetch me some data!

fetch(‘/some/url’) .then(function(response){ return response.json(); }) .then(function(json) {

// something with json }).catch(function(err) {

// error :( });

Fetch me some data!

fetch(‘/some/url’) .then( (response) => response.json() ) .then( (json) => doStuff(json) ) .catch( (error) => handleError(error) );

Template my string

var a = 5; var b = 10; console.log(`Fifteen is ${a+b} and not ${2*a + b}`);

Template my stringvar user = { … }; var html = ` <div> <span>${user.username}</span>

</div> `

Enhanced Object Literals

var obj = { __proto__: protoObj, handler

}

Enhanced Object Literals

var obj = { toString () { return super.toString(); }, [‘prop_’+key()]: key()

}

How to use ES6 NOW

top related