JavaScript — Just another introduction to ES6

Gerard Sans
Sons of JavaScript
Published in
5 min readFeb 22, 2015

Some commented ES6 examples to get you started

From ES6 the awesome parts

JavaScript is gathering a lot of attention since news of Microsoft, IBM and the Linux Foundation announced their support to Node.js just few days ago. It is overdue to bring 2015 modern language features to JavaScript and ES6 is trying to do just that.

Some frameworks like Angular 2.0 are early adopters of ES6

In this post I am going to introduce you to some of these features used in ES6 Fiddle. I recommend you to play with them and get a feeling of what’s to come. These are the features that are being covered:

  • Arrow functions and let keyword; Block scopes
  • Classes and inheritance; Default parameters
  • Destructured assignment
  • Generators; Iterators; Maps
  • Promises; Rest parameters; Sets
  • Spread operator; Template Literals

Let’s get started! You can follow this post with ES6 Fiddle side by side.

Follow me on Twitter for latest updates @gerardsans.

Arrow functions and let keyword

I remember this feature introduced in C# 3.0 few years ago with another name, it was called lambda expressions. In JavaScript this will replace anonymous functions. The best way to go about them is to put both implementations side by side.

Using arrow functions
Using anonymous functions

The code above should be self explanatory. Only note, let is the new keyword applying to a block scope opposed to var that applies to the global scope or a local function. Let’s see the difference with our next example.

Block scope

The difference between var and let is demonstrated in the code below.

Using block scope

In this case the i variable only exists within the for loop, the block scope. In this example, the x variable lives within the global object, but if it was inside a function it would be within the outer function.

Classes and inheritance

Some people argue that JavaScript don’t belong to OO languages but other people still insists on applying OO concepts to it, probably most coming from Java or .NET. To keep diehard-OO-people happy ES6 adds some OO keywords to the mix.

We can see the use of new keywords: class, constructor, extends, super and get. Code is pretty straightforward. From the example we are only missing private/static methods and setters.

Unfortunately there are no keywords for private methods or properties so we have to resort to regular closures or IIFEs.

Besides some small differences the code would translate to:

ES6 is certainly less verbose than current ES5 implementation.

Default parameters

This feature is pretty neat. It allows you to set a default value if none is provided.

Before it was looking something similar to this

Destructured assignment

You might known this feature if you have some Python or PHP experience. There are two types: arrays and objects. For objects the key is used to match the values instead of the position.

This example could be slightly changed to a more common scenario where the object key is different from the target.

Generators

Generators are subtypes of Iterators and use function* and yield together to work their magic. The main idea to take home is that they allow custom iterators implementations. Let’s look at the sample code below

This code creates a generator called range that returns start value as long as is strictly lower that end. After returning the start value to the iterator it increments start with the step value. The generator can only be used within an iterator and as we have seen it creates a block scope.

Iterators for..of

Iterators land to JavaScript land with a similar implementation to IEnumerable in .NET or Java Iterable. In the exemple below it loops through the values in arr Array.

You can use for..of with built-in iterables: String, Array, TypedArray, Map and Set.

Notice how different is from for..in, that loops through object properties.

Maps

Maps substitute objects to store key/value pairs. Pairs are stored as 2-element arrays [key, value].

Maps can use any value as key besides strings but objects can’t.

Some common methods:

map.size       returns its size
map.entries() returns entries in insertion order [k,v]
map.keys() returns just values in insertion order [k]
map.values() returns just values in insertion order [v]

In order to manipulate its content

map.has(key)  // boolean
map.set(key, value)
map.get(key) // value
map.delete(key)

Map implements the in-built iterable so it can be used with for..of.

You should be able to follow the code below now.

Promises

Support for promises is a very nice addition to the language. The example below creates a promise that will call res (resolve) after a second. Then immediately, after that, it will call coolFn logging “cool” to the console.

Rest parameters

Rest parameters remove the need of dealing with the arguments object. The syntax is pretty sleek. It takes a list of parameters converting them to an array. This will be dynamically handled matching the function signature definition. In the example, as format takes two parameters, the first one is taken by str and the rest are put together into args as an array. Very handy!

Sets

Sets are a useful data-type for scenarios where we have to avoid repetitions and use heterogeneous data-types elements (String, Array, Number, etc.). Some common methods are:

set.size       returns its size
set.entries() returns entries in insertion order [v]
set.keys() returns just values in insertion order [v]
set.values() returns just values in insertion order [v]

In order to manipulate its content

set.has(value)  // boolean
set.add(value)
set.delete(value)

See the code below

Spread operator

The spread operator works together with rest parameters in the sense that it takes and array to convert it into a list of parameters. You could rewrite the code as “…[5, 4]” or “…nums”, both equivalent.

Template literals

The best for the end! This feature almost removes the need for a complex template system. It uses the special character `template literal` to delimit a template literal string. We can then inject values into it by using ${value} syntax.

Hope you enjoyed these ES6 fiddle commented examples! Thanks for reading! Have any questions? Ping me on Twitter @gerardsans.

Resources

ES6 Fiddle, Translate ES6 to ES5 online from Babel

--

--

Gerard Sans
Sons of JavaScript

Helping Devs to succeed #AI #web3 / ex @AWSCloud / Just be AWSome / MC Speaker Trainer Community Leader @web3_london / @ReactEurope @ReactiveConf @ngcruise