Everyday ECMAScript 6 – Fat Arrows – Destructuring Arrays



Everyday ECMAScript 6 – Fat Arrows – Destructuring Arrays

0 0


everyday-es6


On Github treyhunner / everyday-es6

Everyday ECMAScript 6

Trey Hunner / @treyhunner

My name is Trey.

Today I'm going to tell you about some new JavaScript features you can use to make your code much more readable.

ECMAScript History

Edition Release Date Browser Support a.k.a. 3 Dec. 1999 All ES3 5 Dec. 2009 IE 9, FF 4, Chrome 7 ES5 6 June 2015 Not supported yet ES2015

First, some terminology.

ECMAScript is the language specification that JavaScript is based on.

ECMAScript 6 is the new version that was finalized last month.

Earlier this year, ECMAScript 6 was renamed to ECMAScript 2015. During this talk I'll use ECMAScript 2015 and ECMAScript 6 interchangeably.

Use next generation JavaScript, today.

This new language spec isn't supported by browsers, but you can start using it today.

You just need to use Babel. Babel allows you to compile your ES6 code down to ES5 code, which is understood by all modern web browsers.

ES2015 features to use today

let declarations template strings object methods fat arrow functions destructuring

So with Babel you can start using most of ECMAScript 6 today. But which features should you use? There are a lot of cool features in ES6, but I'm going to talk about just 4 of them today.

I will be going through these features very quickly, so if you miss something don't worry. My slides are online and I'll be writing a blog post on this topic soon.

Let

// var: function scoping, variables are hoisted
var array = [];
console.log(i); // prints undefined
for (var i = 0; i < 10; i++) {
  array.push(Math.random());
}
console.log(i);  // prints 10

// let: block scoping, no hoisting
let array = [];
console.log(i);  // ReferenceError
for (let i = 0; i < 10; i++) {
  array.push(Math.random());
}
console.log(i);  // ReferenceError

You can now use "let" instead of "var" to define variables. Unlike var, let uses function-level scoping and does not hoist variables.

I highly recommend you switch all uses of "var" to "let".

We'll be using let in the rest of our code examples.

Template Strings

var pageNumber = "( " + getCount() + " / " + pageTotal + " )";

let pageNumber = `( ${getCount()} / ${pageTotal} )`;

If you have ever tried to stick a variable inside a string in JavaScript, you'll know it requires concatenation. Look at all those plus signs and quotes.

With template strings, you can include your variables right inside your string. Just use backticks and you've made a template string.

Methods

var Duck = Backbone.Model.extend({
  name: function name() {
    return "duck";
  },
  sound: function sound() {
    return "quack";
  }
});

let Duck = Backbone.Model.extend({
  name() {
    return "duck";
  },
  sound() {
    return "quack";
  }
});

With the new method syntax, you can remove a lot of the syntax cruft when defining methods. This is great for those of you using an MVC framework.

Notice the lack of the word function. Also note that the functions in these examples are named, not anonymous.

Fat Arrows

promise.then(function (data) {
  return data.response;
}).display();

promise.then(data => data.response).display();

JavaScript loves callbacks. Fat arrow functions allow you to make one-off callback functions with a much simpler syntax.

In this example, we've lost the parenthesis, the curly braces, the return statement, and the word function. This is so much shorter.

Fat Arrows & this

var self = this;
var getValue = function () {
  return self.value;
});

let getValue = () => this.value;

The this variable inside a fat arrow function refers to the same this as outside of it.

No more need to make self or that variables and no need to worry about function binding.

Destructuring Arrays

var numbers = [1, 4, 2, 3];
var x = numbers[0];
var y = numbers[1];
var z = numbers[2];

let numbers = [1, 4, 2, 3];
let [x, y, z] = numbers;

Grabbing a sequence of elements out of an array used to be awkward in JavaScript.

With array destructuring, it's really easy.

This syntax works on anything you can iterate over.

Destructuring Objects

var emoji = {category: "people", char: "😁", name: "smile"};
var char = emoji.char;
var name = emoji.name;
var category = emoji.category;

let emoji = {category: "people", char: "😁", name: "smile"};
let {name, category, char} = emoji;

I just showed you array destructuring. We have a new object destructuring syntax now too.

This new syntax allows you to assign multiple variables to the values of multiple attributes of an object.

Go Forth and Babel

Try it out: http://babeljs.io/repl

http://trey.in/everyday-es6-demo

Okay. I have a mission for you now.

After you go home tonight I want you all to go to Babel website and try it out. Type in some code using the new JavaScript syntax and see what it will convert it to. If you don't have time tonight, try it out this weekend.

You can also go to trey.in/everyday-es6-demo to see how Babel transpiles the ES6 code examples in this talk.

Don't worry, I'll post a link to my slides to Meetup.

Final

http://treyhunner.com/everday-es6

Web consultant available for hire http://truthful.technology

Any questions?

Everyday ECMAScript 6 Trey Hunner / @treyhunner My name is Trey. Today I'm going to tell you about some new JavaScript features you can use to make your code much more readable.

treyhunner.com/everyday-es6