JavaScript meets ES6

JavaScript meets ES6
Reading Time: 7 minutes

What will this article will be about?


You may ask yourself “Why do I need to switch from ES5 to ES6, when it was only released last year and not many of the software products use it?”. Well, it’s simple: Developing software is a continuously evolving domain and the new players that appear need to adapt to the evolution of the technologies.
This article assumes that you already have basic knowledge of JavaScript. To brush up on your JavaScript skills, you can read some of our previous articles, which cover both frontend and backend use of JavaScript (through NodeJS).

Introduction


A little about my journey with JavaScript using ECMAScript 6. When I first started to write some code in JavaScript I was like: “Yeah, I don’t think I’m going to like it so much.”. I was saying that because I was in love with Java ever since I have discovered it. It was like love at first sight. But two months ago, when one of my friends texted me and said: “Dude, have you tried JavaScript with ECMAScript 6?”, I started to do some research… And after that I was like: “I think I found my second love!”.
Now, let’s cut the chase and go to work.

Parameters and Variables


In ES5 for declaring a variable you only use the var keyword, regardless of where you are declaring it: inside or outside a function.

var functionVar = function () {
  // the keyword var is hosting the x variable at the top of the function since
  // var defines function scoped variables
  if (condition) {
    var x= "Old Way";
  }
  console.log(x);
}

Well, ES6 is introducing two new ways of declaring variables.

LET

The let keyword, will let you to define block-scoped variables, as opposed of the function scoped variables that we’ve used until now.

functionLet () {
  // This way let will throw a reference error because it defines
  // block-scoped variables
  if (condition) {
    let x= "New Way";
  }
  console.log(x);
}

Defining this way you will know that the variable it’s only block-scoped and this will make a developer that will read the code for the first time think: “Oh, so this variable is only used in this block, this code is so readable.”.

CONST

A new keyword for defining variables is const. This will define the variable as block-scoped and will be impossible to modify.

functionConst () {
  const x = "Value";    // if you try to modify the variable x it will throw a SyntaxError
  if (condition) {
    x = "New Way";
  }
}

Arrow Functions


This is one of my favorites and I will do my best to make it your favorites, too. Why is that?
When I first started to write code in Java 8, one of the newest functionalities that I noticed were the lambda expressions, which make the code shorter and easier to understand. It’s not rocket science, but this is another story and I will need to tell it in more detail.
After the encounter with lambda expressions in Java 8, I was thinking that it would be awesome if JavaScript would have something like this, because wherever you look in a JavaScript codebase you find that a function receives a function as a parameter. This is a little harder to read for someone whose not familiar with JavaScript syntax and comes from a Java/C# development background.

functionWithoutArrow (param1) {
  setTimeout (function (x) {
  }, 200)
}

The concept of arrow functions will not fundamentally change anything, it will just provide two features.

  • It will be more simple to define an anonymous function
functionWithArrow (param1) {
  setTimeout (() => {
  }, 200);
}
  • It will change the concept of how every functions redefines this. Well, the arrow functions will not have their own this value and that way you don’t have to reassign this to another variable.
functionWithOtherThis (param1) {
  var self = this;
  self.some = 30;
  setTimeout (function () {
    // self will refers to the parent this because it’s assigned to it
    self.new = "Something";
    // this will refer to the this of the anonymous function
    this.new = "Function";
  }, 200);
}

And the way this is used in ES6 within arrow functions:

functionWithThisArrow (param1) {
  setTimeout (() => {
    // this will refer to the parent this
    this.new = "Function";
  }, 200);
}

So basically, it will be less code, easy to read and kind of awesome. Have I said we love making thinks as simple as possible?

Asynchronous Programming (Promises)


Let me guess, you guys have the same desire like me: that when developing an application, another independent activity like food being prepared or a massage on your neck and other activities of the like will not interfere with your developing. Well… you have to pray for it.
So ECMAScript 6 brings promises, in the sense that an operation is executed asynchronous and it will not interfere with other operations. If you don’t want to use promises, you can accomplish the same behavior using callbacks, but a huge advantage of using promises is providing a more readable code by chaining the methods and the system for error handling.
Promises in JavaScript are currently provided by many libraries like Q.js, $q (a service from Angular) and RSVP.js.

getJSON("/URL/").then(function(post) {
  return getJSON(post.comments);
  }).then(function(comments) {
    // do stuff
  }).catch(function(error) {
    // handle errors
});

So, the new look of promises in ES6 will give you a clear concept of what you are using and dealing with. First, you are defining a promise with two parameters, resolve and reject. The resolve will be returned as a variable of any type, only if the asynchronous operation has successfully ended. The reject will be returned in case of a thrown error.

var p1 = new Promise((resolve, reject) => setTimeout(resolve, 4, "first"));

The syntax for calling a promise in ECMAScript 6 is not different from the one of other JavaScript libraries.

p1.then((some) => {
  // do stuff
}).then((comments) => {
  // do other stuff
}).catch((message)=> {
  // in case of an error it will be logged
  console.log(message);
})

Modules


This feature will bring a change for many applications that were developed in JavaScript, by modifying the structure and make it… well, more modular. There are a few good solutions for JavaScript using ECMAScript 5 to achieve this and some 3rd party libraries like node modules or CommonJS.
For me, this feature is awesome because at the beginning of every JavaScript file you have to import the dependencies that are needed for that module.

import $ from 'lib/jquery';

But of course with an import keyword an export keyword will come along, this way you will export some things from the module.

export const sqrt = Math.sqrt;

The goals of the module feature are:

  • easier asynchronous external loading
  • simplicity
  • usability
  • fast compilation
  • refactoring the modules will be more smooth
  • compatibility with browsers and non-browsers

Classes


And last, but not least, a very important feature. The appearance of classes in JavaScript will create the feel that you are coding in Java. When I first wrote a class in JavaScript I renamed the extension to .java, sent the file to one of my friends, and I asked: “Mihai, what do you think of my code?”. He said: “It’s pretty good written, you did a good job.”, he didn’t even notice that it was developed in JavaScript at first. Anyway, enough with the stories. Here is how the magic happens.
Using ECMAScript 5 you can shadow the creation of the class by creating a function that acts as a constructor and after that calling the function with the new keyword.

function Car(speed) {
  this.speedCar = function () {
    // do stuff
  }
}
var newCar = new Car(150);
newCar.speedCar();

But the real magic will happen in ECMAScript 6. Take a closer look:

class Car {
  constructor() {
    // constructor for the class
  }
  function1() {
  }
}
class Car2 extends Car {
  constructor(speed, make) {
  }
}
let newCar = new Car2(150, "SomeKind");

Not a Conclusion


There will be no conclusion because I think you’ve already formed your own opinion about it. I hope you guys will like JavaScript using standards of ECMAScript 6, just like I do.
Hungry for more? We love using Javascript and writing about it, so you can delve into our articles on using NodeJS to build an API and an Admin Panel in a matter of minutes, or delve into topics such as Javascript number overflow validation, animations or charts.

We transform challenges into digital experiences

Get in touch to let us know what you’re looking for. Our policy includes 14 days risk-free!

Free project consultation