Get Started with ECMAScript 6

Andrew Chalkley

June 17, 2015

-

5 min read

Learn

ECMAScript 6 or ES6 is the latest standardized version of JavaScript. The exciting thing is it’s been approved today by the standards body and that means broader browser support is coming. ECMAScript 6 has been in the works for some time now – it was first announced in 2008. An ever increasing amount of JavaScript developers have been preparing for ECMAScript’s launch, and soon it’ll be unavoidable. It’s also worth noting not all versions of ECMAScript will take this long to release. They plan on doing smaller, yearly releases, so now’s a good time to get up to speed.

Many developers have switched to ECMAScript 6 in development and use a transpiler, a ES6 source to ES5 source compiler, to publish their code to browsers and environments that don’t support ES6 features yet.

Let’s see some of the main ES6 features you can use today using a transpiler and will be available in a browser near you soon!

Object Literals

Take this common JavaScript example:

function createPerson(firstName, lastName) {
return {
firstName: firstName,
lastName: lastName
}
}
view raw gistfile1.js hosted with ❤ by GitHub

When you call the createPerson function it creates an object literal with the keys of firstName and lastName.

In ES6 you can do the shorthand of:

function createPerson(firstName, lastName) {
return {
firstName,
lastName
}
}
view raw gistfile1.js hosted with ❤ by GitHub

Classes

JavaScript is a prototype-based object oriented language which means to describe something like a Song in a hypothetical playlist application we’d need to write something like this:

function Song(title, artist, duration) {
this.title = title;
this.artist = artist;
this.duration = duration;
this.isPlaying = false;
}
Song.prototype.start = function start() {
this.isPlaying = true;
};
Song.prototype.stop = function stop() {
this.isPlaying = false;
};
view raw gistfile1.js hosted with ❤ by GitHub

ES6 has introduced a class syntax which looks like other languages. However, it’s still prototypal underneath:

class Song {
constructor(title, artist, duration) {
this.title = title;
this.artist = artist;
this.duration = duration;
this.isPlaying = false;
}
start() {
this.isPlaying = true;
}
stop() {
this.isPlaying = false;
}
}
view raw gistfile1.js hosted with ❤ by GitHub

Default Values

In the previous example, I showed you how to write a class in ES6, where I set the isPlaying property to be false. While this guarantees isPlaying is false, how about when I want to create an instance that’s playing immediately?

ES6 introduces the concept of default values to any function or method call.

Here’s an updated example with the isPlaying set to false:

class Song {
constructor(title, artist, duration, isPlaying = false) {
this.title = title;
this.artist = artist;
this.duration = duration;
this.isPlaying = isPlaying;
}
start() {
this.isPlaying = true;
}
stop() {
this.isPlaying = false;
}
}
view raw gistfile1.js hosted with ❤ by GitHub

If isPlaying is given a value when the object is created it will be false, alternatively you can pass in true to override it.

var song = new Song("Wonderwall", "Oasis", "3:45");
song.isPlaying === false;
var song2 = new Song("Song 2", "Blur", "2:02", true);
song2.isPlaying === true;
view raw gistfile1.js hosted with ❤ by GitHub

Inheritance

Inheritance has been simplified too. There were a number of things you had to remember to do, for example calling the call method on the constructor you’re inheriting from, and you have to wire up the prototype chain. You’d have to write something like this:

function Media(title, duration) {
this.title = title;
this.duration = duration;
this.isPlaying = false;
}
Media.prototype.start = function start() {
this.isPlaying = true;
};
Media.prototype.stop = function stop() {
this.isPlaying = false;
};
function Song(title, artist, duration) {
Media.call(this, title, duration);
this.artist = artist;
}
Song.prototype = Object.create(Media.prototype);
function Movie(title, year, duration) {
Media.call(this, title, duration);
this.year = year;
}
Movie.prototype = Object.create(Media.prototype);
view raw gistfile1.js hosted with ❤ by GitHub

Now you can use the extends keyword and super to wire everything up with the “superclass”.

class Media {
constructor(title, duration, isPlaying = false) {
this.title = title;
this.duration = duration;
this.isPlaying = isPlaying;
}
start() {
this.isPlaying = true;
}
stop() {
this.isPlaying = false;
}
}
class Song extends Media {
constructor(title, artist, duration, isPlaying = false) {
super(title, duration, isPlaying);
this.artist = artist;
}
}
class Movie extends Media {
constructor(title, year, duration, isPlaying = false) {
super(title, duration, isPlaying);
this.year = year;
}
}
view raw gistfile1.js hosted with ❤ by GitHub

Arrow Function

this can be tricky. Especially, in the context of functions within functions.

Let’s look at the following example:

class Contact {
constructor(name, email, button) {
this.name = name;
this.email = email;
button.onclick = function(event) {
sendEmail(this.email);
}
}
}
view raw gistfile1.js hosted with ❤ by GitHub

I want to use a sendEmail function when a button is pressed and I pass in the this.email it should be the email from the instance of the contact, but this in that context is the button. Some people assign this to a variable outside the scope like this:

class Contact {
constructor(name, email, button) {
this.name = name;
this.email = email;
var that = this;
button.onclick = function(event) {
sendEmail(that.email);
}
}
}
view raw gistfile1.js hosted with ❤ by GitHub

There is a new way to create functions, using an arrow, like this:

class Contact {
constructor(name, email, button) {
this.name = name;
this.email = email;
button.onclick = (event) => {
sendEmail(this.email);
}
}
}
view raw gistfile1.js hosted with ❤ by GitHub

It’s also useful to create simple functions inline too.

var oneToFive = [1,2,3,4,5];
var twoToTen = oneToFive.map((n) => n * 2);
console.log(twoToTen); //[2,4,6,8,10]
view raw gistfile1.js hosted with ❤ by GitHub

You don’t need to include parentheses for single parameter functions either.

var oneToFive = [1,2,3,4,5];
var twoToTen = oneToFive.map(n => n * 2);
console.log(twoToTen); //[2,4,6,8,10]
view raw gistfile1.js hosted with ❤ by GitHub

Note it also returns aren’t required.

The let Keyword

The let keyword declares a local variable in the block scope. Normally if statements don’t have scope, but now they do with let. This can be helpful when you want to do lots of work on a variable and don’t want to pollute another scope with more variables than they need.

var x = 1;
if(x < 10) {
let v = 1;
v = v + 21;
v = v * 100;
v = v / 8;
console.log(v);
}
console.log(v); //v is not defined
view raw gistfile1.js hosted with ❤ by GitHub

This also works for loops too.

for (let i = 0; i < 10; i++) {
console.log(i); // 0, 1, 2, 3, 4 ... 9
}
console.log(i); // i is not defined
view raw gistfile1.js hosted with ❤ by GitHub

The const Keyword

A const or a constant declaration is where once, the variable is set you can’t change it. It’s read-only.

const admin = "Andrew";
admin = "Kenneth"; // "admin" is read-only
view raw gistfile1.js hosted with ❤ by GitHub

However, properties on object’s aren’t protected so you could do something like this:

const admin = {name: "Andrew"};
admin.name = "Kenneth";
view raw gistfile1.js hosted with ❤ by GitHub

Template Strings

Concatenating strings are a pain in JavaScript. As the length of your string increases, your pain increases too.

Whether you do it like this:

class Contact {
constructor(name, email, button) {
this.name = name;
this.email = email;
}
toEmailClientString() {
return this.name + " <" + this.email + ">";
}
}
view raw gistfile1.js hosted with ❤ by GitHub

Or like this:

class Contact {
constructor(name, email, button) {
this.name = name;
this.email = email;
}
toEmailClientString() {
var clientString = this.name;
clientString += " <";
clientString += this.email;
clientString += ">";
return clientString;
}
}
view raw gistfile1.js hosted with ❤ by GitHub

It’s really annoying, repetitive and (human) error prone.

With ECMAScript there’s a new way using template strings. A template string starts and ends with a backtick (`). Each variable that you’d like inserting into the string is wrapped in a ${}. Like so:

class Contact {
constructor(name, email, button) {
this.name = name;
this.email = email;
}
toEmailClientString() {
return `${this.name} <${this.email}>`;
}
}
view raw gistfile1.js hosted with ❤ by GitHub

String templates can also be multiline too.

class Media {
constructor(title, duration, isPlaying = false) {
this.title = title;
this.duration = duration;
this.isPlaying = isPlaying;
}
start() {
this.isPlaying = true;
}
stop() {
this.isPlaying = false;
}
}
class Song extends Media {
constructor(title, artist, duration, isPlaying = false) {
super(title, duration, isPlaying);
this.artist = artist;
}
toString() {
return `<li>
${this.title} - ${this.artist} <span>${this.duration}</span>
</li>`;
}
}
view raw gistfile1.js hosted with ❤ by GitHub

Destructuring

Destructuring is an awesome way to extract values from arrays and objects.

Let’s take a look at an example for an array being destructured.

var [first, second, third] = ["Andrew", "Craig", "Kenneth"];

So first is "Andrew", second is "Craig" and finally there is "Kenneth".

For objects, like this:

var person = {
firstName: "Andrew",
lastName: "Chalkley"
}
var {firstName, lastName} = person;
view raw gistfile1.txt hosted with ❤ by GitHub

This is the equivalent of:

var person = {
firstName: "Andrew",
lastName: "Chalkley"
};
var firstName = person.firstName;
var lastName = person.lastName;
view raw gistfile1.js hosted with ❤ by GitHub

You don’t have to use the same name as the key, you can do something like this:

var person = {
firstName: "Andrew",
lastName: "Chalkley"
}
var {firstName: first, lastName: last} = person;
view raw gistfile1.js hosted with ❤ by GitHub

Where first is "Andrew" and last is "Chalkley".

This can be helpful when you know you’re getting an object as a parameter in a function call.

var person = {
firstName: "Andrew",
lastName: "Chalkley"
}
function getFirstName({firstName: first}) {
return first;
}
getFirstName(person); //Returns "Andrew"
view raw gistfile1.js hosted with ❤ by GitHub

The getFirstName(person); line will return “Andrew".

Rest & Spread

Let’s say we have an array of runners and if you don’t place first, second or third, you don’t get any medals, you’re losers. You can use the rest prefix of ... to extract the rest of the arguments from a function call. On the other side, we can use the spread prefix of ... to spread out array into all the possible arguments the function call could have.

var runners = ["Mary", "Andrew", "Craig", "Michael", "Kenneth", "Dave"];
function getLosers(first, second, third, ...losers) {
return losers;
}
getLosers(...runners);
view raw gistfile1.js hosted with ❤ by GitHub

Mary won, Andrew came second and Craig was third. Unfortunately for ["Michael","Kenneth","Dave"] they were losers. Better luck next time guys!

Conclusion

We’ve just scratched the surface of the major syntactical changes and improvements in ES6. ES6 is backwardly compatible so you can still write how you would today. But there are maintenance and productivity advantages with the new syntax. There are new native object types in ECMAScript 6. I’ll write about those another time.

If you’re wanting to try these examples yourself or try it out in the browser you can visit Babel’s “Try it out” section. Babel is a transpiler you can use to convert ECMAScript 6 to ECMAScript 5. You can install it through NPM and start using ES6 in your projects today!

16 Responses to “Get Started with ECMAScript 6”

  1. This is a great getting started tutorial for any one who want to start learning ES6, I find it a must have skill for any javascript developer. Thank you for this great article.

  2. Awesome article 🙂

  3. Riccardo M on January 26, 2017 at 12:09 am said:

    Thank you for this short Tutorial. It helped me a lot! 🙂
    Greets from Germany

  4. Hi! I want to ask is there some transpile to convert my ES 5 to ES 6. I am interesting from the opposite of Babel..

  5. Volodymyr Prezliata on July 30, 2016 at 9:35 am said:

    Clear & easy, great job!

  6. Shereej Ponmily on July 15, 2016 at 3:45 am said:

    Thank you Andrew Chalkley for taking effort on publishing this.
    This article is very much informative and i appreciate it and will definitely try this one.

  7. Chris on July 4, 2016 at 5:06 pm said:

    This is a fantastic, clear and easy to understand tutorial. I have a friend, and he’s been telling me to use ecmascript for a while now, and I finally got around to checking it out.

    This tutorial is perfect, thank you!

  8. Fantastic write up Andrew. Thanks a lot!

  9. Ravishankar Radhakrishnan on September 25, 2015 at 8:04 am said:

    This is the best clear and crisp ES6 Tutorial I have come across so far. Thanks Andy.

  10. Very useful, thanks a bunch! ♥

  11. Joseph Graham on June 22, 2015 at 3:54 pm said:

    please upload ECMAScript 6 or ES6 video tutorials

  12. Nejc Vukovic on June 22, 2015 at 1:06 pm said:

    Go Andrew. “The JS Master”!

  13. Thanks for the Article Andrew! Do you know if/when the Tree will be updating their JS course or adding a special ECMAScript 6 update course?

  14. Thank you for the awesome intro to ECMAScript 6! I will definitely be using these features!

Leave a Reply

You must be logged in to post a comment.

You might also like other posts...

Want to learn more about Javascript?

Learn how to use JavaScript to add interactivity to websites.

Learn more