by Todd Palmer

Getting started with ES6 using a few of my favorite things

Forest Path in Western Finland by Miguel Virkkunen Carvalho

This tutorial walks you through some easy steps to get started learning the newest version of JavaScript: ES6.

To get a feel for the language, we will delve into a few of my favorite features. Then I will provide a short list of some great resources for learning ES6.

ES6 or ECMAScript 2015?

“What’s in a name?”
― Juliet from Shakespeare’s “Romeo and Juliet”

The official name of the 6th Edition of ECMAScript is ECMAScript 2015, as it was finalized in June, 2015. However, in general, people seem to refer to it simply as ES6.

Previously, you had to use a transpiler like Babel to even get started with ES6. Now, it seems that just about everybody except Microsoft Internet Explorer supports most of the features in ES6. To be fair, Microsoft does support ES6 in Edge. If you want more details, take a look at kangax’s compatibility table.

ES6 Learning Environment

The best way to learn ES6 is to write and run ES6. There are may ways to do that. But the two that I use when I am experimenting are:

Node.js and Visual Studio Code

One of the best ways to explore the pleasantries of ES6 is to write your code in an editor like Visual Studio Code and then run it in Node.js

Install Visual Studio Code and create a file called helloworld.js. Paste the following code in:

console.log('Hello world');

Save it. It should look something like this:

Since version 6.5, Node.js has supported most of the ES6 standard. To run our example, open the Node.js Command Prompt to your folder where you created the helloworld.js file. And, just type:

node helloworld.js

Our console.log statement prints as output:

Babel.io

It isn’t as much fun as Node.js, but a convenient way to run ES6 code is the Try it out page on Babel.io. Expand the Settings and make sure Evaluate is checked. Then open your browser Console.

Babel REPL

Type the ES6 into the column on the left. Babel compiles it to plain old JavaScript. You can use console.log and see the output in the Web Console on the right.

Some of My Favorite Features

“These are a few of my favorite things.”
― Maria from Rodgers and Hammerstein’s “The Sound of Music”

In this section, we will take a quick look at just a few of the new features of ES6 including:

  • Using let and const instead of var
  • Arrow functions
  • Template Strings
  • Destructuring

const and let Versus var

Now that you are coding in ES6: Stop using var! Seriously, never use var again.

From now on, use either const or let. Use const when you will set the value once. Use let when you intend to change the value.

let bar = { x: 'x'};const foo = { x: 'x'};
bar.x = 'other'; // This is finefoo.x = 'other'; // This is fine
bar = {}; // This is also finefoo = {}; // This will throw an error

Typically, I like to use const first. Then if it complains, I look at my code and make sure I really need to be able to modify the variable. If so, I change it to let.

Make sure you check out the resources later in this article for more information on let and const. You will see that they work much more intuitively than var.

Arrow Functions

Arrow functions are one of the defining features of ES6. Arrow functions are a new way to write functions. For example, the following functions work identically:

function oneMore(val){  return val+1;}console.log('3 and one more is:', oneMore(3));
const oneMore = (val) => val+1;console.log('3 and one more is:', oneMore(3));

There are a few things to remember about arrow functions:

  • They automatically return the computed value.
  • They have lexical this.

This first time I saw this I wondered, “What in the wide world is a lexical this? And, do I really care?” Let’s look at an example of why the lexical this is so useful and how it makes our code so much more intuitive:

In lines 1–31, we define a Class called ThisTester. It has two functions thisArrowTest() and thisTest() that basically do the same thing. But, one uses an arrow function and the other uses the classic function notation.

On line 33, we create an new object myTester based on our ThisTester class and call the two functions in our class.

const myTester = new ThisTester();console.log('TESTING: thisArrowTest');myTester.thisArrowTest();console.log('');console.log('TESTING: thisTest');myTester.thisTest();

In the thisTest() function, we see that it tries to use this in line 26.

console.log('function this fails', this.testValue);

But, it fails because that function gets its own this and it isn’t the same this as the class. If you think this is confusing, that’s because it is. It isn’t intuitive at all. And, new developers sometimes spend their first week fighting with this in callback functions and promises like I did.

Eventually, after reviewing a bunch of examples, I figured out the standard “trick” of using a variable called self to hold onto the this that we want to use. For example, in line 17:

let self = this;

However, notice how in the arrow function in line 10, we can directly access this.testValue and magically it works:

let myFunction = (x) =>console.log('arrow "this" works:', this.testValue)

That is lexical this in action. The this in the arrow function is the same as the this in the surrounding function that calls it. And hence we can intuitively use this to access the properties in our object like this.testValue.

Template Strings

Template Strings (sometimes called Template Literals) are an easy way to construct strings. They are great for multi line strings such as those used in Angular templates. Template Strings use the back tick ` instead of quote or apostrophe.

Here is an example of creating a long, multi-line string:

const myLongString = `This stringactually spans many lines.And, I don't even need to use any "strange"notation.`;console.log (myLongString);

You can easily bind variables to your string, for example:

const first = 'Todd', last = 'Palmer';console.log(`Hello, my name is ${first} ${last}.`)

Looking at that variable assignment begs the question:
“What if I need to use the $, {, or } characters in my string?”

Well, the only one that needs special treatment is the sequence ${.

console.log(`I can use them all separately $ { }`);console.log(`$\{ needs a backslash.`);

Template Strings are especially useful in Angular and AngularJS where you create HTML templates, because they tend to be multi-line and have a lot of quotes and apostrophes. Here is what a small example of an Angular Template leveraging the back tick looks like:

import { Component } from '@angular/core';
@Component({  selector: 'app-root',  template: `    <h1>{{title}}</h1>    <h2>My favorite hero is: {{myHero}}</h2>  `})export class AppComponent {  title = 'Tour of Heroes';  myHero = 'Windstorm';}

Destructuring

Destructuring lets you take parts of an object or array and assign them to your own named variables. For more information on Destructuring, check out my article on ITNEXT.

ES6 Resources

That was just a quick overview of a few of the new features in ES6. Here are some great resources for continuing your journey down the path of learning ES6:

This article is based on a lecture I gave in March 2018.