paint-brush
Beginner Bites: ES6 features you need to knowby@spyr1014
4,042 reads
4,042 reads

Beginner Bites: ES6 features you need to know

by Andrew JakubowiczDecember 19th, 2016
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

You’re familiar with native JavaScript and have created some applications using it, but when you venture into the broader ecosystem there is JavaScript that looks foreign. Especially in the documentation for the libraries you hear about often like “React”, “Redux”, “TypeScript”, “Angular”, “Ember”, &lt;<em>insert cool framework/library here</em>&gt;. Something I personally found difficult was learning any new library due to the knowledge dependency of needing to understand this future JavaScript language, ES6.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Beginner Bites: ES6 features you need to know
Andrew Jakubowicz HackerNoon profile picture

You’re familiar with native JavaScript and have created some applications using it, but when you venture into the broader ecosystem there is JavaScript that looks foreign. Especially in the documentation for the libraries you hear about often like “React”, “Redux”, “TypeScript”, “Angular”, “Ember”, <insert cool framework/library here>. Something I personally found difficult was learning any new library due to the knowledge dependency of needing to understand this future JavaScript language, ES6.

In this post I hope to cover the future JavaScript features using JSBin to test drive them, providing examples and exercises. This post is aimed at beginners who want to be exposed to the most important parts of ECMAScript6 (in order to read and understand documentation for the modern libraries used today).

We’ll cover:

  • Arrow functions
  • Rest parameters
  • Destructuring assignment
  • Template literals
  • Classes
  • Promises
  • Generators

I recommend using JSBin to test out these examples! (Make sure you change the JSBin language to ES6 / Babel)

Arrow Functions

Arrow functions can be thought of a shorthand way to write functions. The two functions below are equivalent:



var fn1 = function (a) {return 2 * a}

var fn2 = a => 2 * a;

Play with the above example live.

You’ll notice a couple things with the arrow function above.

First, the arrow function lacks parenthesis around the arguments. This is because there is only a single argument a. If we want to pass in multiple arguments we’d need those parenthesis back.

var fn3 = (a, b) => a + b;

Secondly, you’ll also notice the implicit return of the right hand side of the arrow. The right hand side of the arrow is a shorthand of return a + b;. What if we want to do more things inside the arrow function than just a single return line? We reintroduce the {} brackets.




var fn4 = (a, b) => {var result = a + b;return result}

Finally, if you want to implicitly return an object, you’ll have a problem. The curly braces around the object literal notation interfere with the curly brackets that declare the function body. In this case you need to wrap the object with parenthesis.


// Incorrect return of object literal notation.var fn5 = () => { name: 'Bob' };


// Correct return of object literal notation.var fn6 = () => ({ name: 'Bob' });

Some other points worth investigating:

Rest Parameters

Rest Parameters are a way of capturing any number of arguments passed into a function in an array. This is similar to arguments but will give you an actual array.





var fn7 = (a, b, ...theRest) => {console.log(a);console.log(b);console.log(theRest);}

fn7('A', 'B', 'C', 'D', 'E');

Play with the rest parameter.

The rest parameter must be the final parameter in the list of parameters. This ... syntax can also be used the other way, destructuring an array.

Destructuring assignment

This allows the spreading of arrays or objects into distinct variables. In the example above we’re calling fn7 with ’A’, ‘B’, ‘C’, ‘D’, ‘E’. We could store those letters in an array. But if we pass an array into the function we end up assigning the array to a, instead of splitting the array up over the function parameters. Here is the ideal use case of the destructuring assignment syntax, where we add ... before the array to destructure it.

var someArray = [’A’, ‘B’, ‘C’, ‘D’, ‘E’];

// Using fn7 defined above.


// Destructuring assignment. This will split 'someArray'.fn7(...someArray);

/** WRONG **/ fn7(someArray);

Play with destructuring live.

Other fun things to try using destructuring syntax are shown in the MDN documentation. The  is called Spread Syntax.

Template literals

This is another way of writing string literals but allowing you to embed expressions into the string. Strings are enclosed within ' or " . A template literal is enclosed within back-ticks `. Expressions embedded within the template string sit within ${} brackets.


var name = 'Mia';console.log(`Hi my name is ${name}.`);

Template literals feature:

  • multiline
  • have a raw property allowing you to access the raw string
  • output modification using tagged template literals

Live example of template literals.

Classes

A simple class can be defined like so:

class Monster {



constructor(name){this.name = name;}




greetings(){console.log(`Hi my name is ${this.name}.`);}}

var goblin = new Monster('Jerry');

goblin.greetings();

A class has a constructor that is called when you call new Monster. In this class the constructor expects a single argument name. This name is assigned to this.name which is a variable assigned to the instance created.

Live example of a basic class.

This is a fantastic article on classes, and I recommend you dig deeper.

Promises

Before explaining what a promise is, I’ll try to explain what problem promises solve.

You’re coding a weather application that allows users get the current weather at a given location. There is a server that responds with the temperature after you call it, but it can take some time. If your program waits for the temperature to be provided by the server, it will freeze until the temperature is provided. An alternative is promising that one day the value will exist. Then doing something with the value after it resolves. If an error occurs the promise can reject and you can catch the error.

Spend some time looking at this example and try the exercise.

Promises have entire posts devoted to them, so I’ll link some material that helped me understand them.

Generators

Generators are a function that can pause execution and then continue where they left off. This is fantastic for when you need to seperate logic and timing.

A great example for when I used generators is when creating the animation for Interactive Maze Solver. This allowed me to animate a simple recursive path finding algorithm, but then freeze / unfreeze it to draw each individual frame.

A generator function is declared using function* in the function declaration like so:

function* generatorDefinition(){ /** stuff here **/ };

A generator function uses yield instead of return to pause execution and yield a value. To yield a value from your generator call .next() on the iterator returned from the generator. This returns an object with two properties (‘done’ and ‘value’). When the iterator encounters a return statement it finishes, returning done: true as well as the value.

Use yield* within your generator to call another generator function. This is how you write a recursive generator.

To summarise:

  • A generator returns an iterator.
  • Calling .next() on the iterator returns an object with two properties. ‘done’ and ‘value’.
  • Generators can be recursive by using yield*.






function* trivialGenerator() {var i = 0;while (true) {yield i++;}}

var myIterator = trivialGenerator();


console.log(myIterator.next());console.log(myIterator.next());

Play with a live example here and try the exercises.

Congratulations if you got this far! You should definitely pat yourself on the back. You’ve now been exposed to the major changes to the language that people are using. As a reward have a cheat sheet that summarises ES6.

Happy hacking!

Edit 20/12/2016: Reworded intro, and corrected some typos that were pointed out.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!