Click here to Skip to main content
14,699,541 members
Articles » Web Development » Client side scripting » JavaScript
Article
Posted 28 Jun 2016

Stats

4K views
2 bookmarked

ECMAScript 6: How-to Guide to New Attractive Features

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
28 Jun 2016CPOL
The article is to have a closer look at the new features introduced by ECMAScript 6 and give examples of how they can be used by developers.

ECMAScript 6 - The latest standardized version of JavaScript adopted in June 2015. At the moment, features of ES6 are just partially available through modern browsers. Useful information gathered in ES6 compatibility table reflects the new features supported by browsers and transpilers.

Let's take a look at the 10 most important innovations, although ES6 provides much more. To access the advanced features, you can:

  • use a modern browser with ECMAScript 6 support (e.g. Google Chrome version 47), but be sure to add 'use strict' instruction in js files
  • use ECMAScript 6 by installing Gulp-Babel plugin
  • use Babel transpiler. Enter ECMAScript 6 code on the left side, and it will be converted into ECMAScript 5 on the right side.

Let's have a look into the details.

1. The let Keyword

Variables defined by the let keyword have a number of advantages:

  • Given this way, the variable is visible only within the block
  • Variable let cannot be used until it has been declared
console.log(name); // error

                         let name = 'John';

By declaring the let variable in a “for” or “while” loop, it will be only active within the loop itself. The same is true about if blocks:

for (let num = 5; num < 10; num++) {
    console.log(num); // 5, 6, 7, 8, 9
}

console.log(num); // num is not defined

var number = 1;

if(number < 10) {
    let v = 1;
    v = v + 21;
    v = v * 100;
    v = v / 8;

    console.log(v);
}

console.log(v); //v is not defined

It is important to note that it is forbidden to declare let variable twice. The following example leads to the error:

let name;
let name; // error

2. Classes

To describe a class in earlier versions of JavaScript, it was necessary to write the following:

function Product(price, category, description) {
    this.price = price;
    this.category = category;
    this.description = description;
    this.isPublished = false;
}

Product.prototype.publish = function publish() {
    this.isPublished = true;
};

Product.prototype.unpublish = function unpublish() {
    this.isPublished = false;
};

In ECMAScript 6, to declare a class, one should use keywords class and constructor. Now you can as well inherit new classes using the "class Child extends Parent" syntax, which might be familiar to you because of other object-oriented programming languages (e.g. PHP). Static methods can also be declared in classes. Let’s take the following example as illustration to the statement:

class Product {
  constructor(price, category, description) {
    this.price = price;
    this.category = category;
    this.description = description;
    this.isPublished = false;
  }

  publish() {
    this.isPublished = true;
  }

  unpublish() {
    this.isPublished = false;
  }

  static getDate() {
    return new Date();
  }
}

class DownlowdableProduct extends Product{
    // your code goes here
}

To create an instance of the class, you can use keyword new.

3. Default Values

ES6 introduces the possibility to set default values for parameters. The syntax of this feature is self-explanatory. The default values are specified when function is called. Here is an example, where isPublished is set by default:

   class Product {
        constructor(price, category, description, isPublished = false) {
        this.price = price;
        this.category = category;
        this.description = description;
        this.isPublished = isPublished;
    }

    publish() {
        this.isPublished = true;
    }

    unpublish() {
        this.isPublished = false;
    }
}

Expressions can be set as default values for parameters.

function sayHello(name = getCurrentUser().toUpperCase()) {
    console.log('Hello, ' + name);
}

function getCurrentUser() {
  return 'Guest';
}

sayHello();

4. The const keyword

To declare a constant, you can use const keyword, thus creating a variable that cannot be changed:

const MAX_NUM = 5;
MAX_NUM = 10; // error

Note that if an object is assigned to constant, you cannot change the very constant, but you can modify properties within it. This also applies to arrays or other object values.

const person = {
  screenName: "Guest"
};

person.screenName = "John"; // available
person = 5; // error

5. Template Strings

ECMAScript 6 has a new way of specifying template strings: they begin and end with quotation mark (`).

let string = `New String`;

In case you use single and double quotation marks, it is allowed to use new lines and substitute expressions using braces ${variable}.

class Product {
  constructor(price, description, isPublished = false) {
    this.price = price;
    this.description = description;
    this.isPublished = isPublished;
  }

  publish() {
    this.isPublished = true;
  }

  unpublish() {
    this.isPublished = false;
  }
}

class DownlowdableProduct extends Product {
  constructor(price, link, title, description, isPublished = false) {
    super(price, description, isPublished);
    this.link = link;
    this.title = title;
  }

  toString() {
    return `<li>
          ${this.title} - ${this.link} <span>${this.price}</span>
        </li>`;
  }
}

6. Destructuring

Destructuring is a convenient way of extracting values from data stored in (possibly nested) objects and arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

var [firstName, lastName, city] = ["John", "Doe", "Moscow"];

So firstName includes "John", lastName - "Doe" and city - "Moscow".

If you want to discard unwanted items, you need to put an extra comma:

let [, , lastName] = "Hello John Doe".split(" "); // first and second elements will be ignored
     console.log(lastName); // Doe

For objects, the code will be as follows:

var contact = {
  email: "john@mail.com",
  url: "http://google.com"
}

var {email, url} = contact;

This code is similar to the following:

var contact = {
  email: "john@mail.com",
  url: "http://google.com"
};

var email = contact.email;
var url = contact.url;

You can easily split into variables an array or an object, which in turn contain other arrays or objects.

let settings = {
  params: {
    w: 100,
    h: 200
  },
  elements: ["Home", "Contact Us"]
}

let { title="Menu", params: {w, h}, elements: [item1, item2] } = settings;

console.log(title);  // Menu
console.log(w);  // 100
console.log(h); // 200
console.log(item1);  // Home
console.log(item2);  // Contact Us

7. Object Literals

Consider a typical JavaScript example:

function makeRequest(method, url) {
    return {
        method: method,
        url: url
    }
}

Object literal will be created with method and url keys when makeRequest function is called. In ECMAScript 6, the same can be done in a shorter way:

function makeRequest(method, url) {
    return {
        method,
        url
    }
}

8. Symbols

Symbol - the type of data, similar to Number and String, which can be used to generate unique identifiers. Every symbol is unique.

let unique = Symbol(‘sym’);

Note that the Symbol is used without the keyword new, as it is primitive type. This function can be used to create unique constants.

const FIRST = Symbol('my symbol');
const SECOND = Symbol('my symbol');

typeof FIRST === 'symbol'; // true
FIRST === SECOND; // false

The optional argument description can be used to describe the symbol and is useful for debugging:

let unique = Symbol("sym");  console.log( unique.toString() ); // Symbol(sym)

9. Rest & Spread

To obtain an array of arguments, it became possible to use the operator ... as shown below:

function printInfo(first, last, ...other) {
  console.log(first + ' ' + last + ' - ' + other);
}

printInfo("John", "Doe", "student"); // John Doe - student

In other will be written an array of arguments, starting with the second one. It can be seen that other is a normal array which uses standard methods such as map, forEach and other, which are not available for arguments pseudoarray .

Operator … must always be at the end and can be used to read the parameters in the function declaration. It can as well be applied when calling a function to pass an array of parameters in form of a list:

let nums = [9, 3, 20];
let maxNumber = Math.max(...nums);
console.log( maxNumber ); // 20

10. Arrow Function

Let's look at the following example:

class Contact {
  constructor(attachment, mail, sender) {
    this.attachment = attachment;
    this.mail = mail;

    sender.onclick = function(event) {
      sendEmail(this.mail);
    }
  }
}

When I press the button, I want to use sendEmail function and pass it a parameter this.mail. But this will be used in the context of the sender, and not in the context of a Contact. Some people assign this variable out of scope:

class Contact {
  constructor(attachment, mail, sender) {
    this.attachment = attachment;
    this.mail = mail;
    var that = this;
    sender.onclick = function(event) {
      sendEmail(that.mail);
    }
  }
}

There is a new way to create a function, using the arrow:

class Contact {
  constructor(attachment, mail, sender) {
    this.attachment = attachment;
    this.mail = mail;
    sender.onclick = (event) => {
      sendEmail(this.mail);
    }
  }
}

Thus, it is possible to create simple functions.

var numArray = [2,4,6,8,10];
var newNumArray = numArray.map((elem) => elem * 2);
console.log(newNumArray); // [4,8,12,16,20]

Conclusion

Support for ECMAScript 6 is still very limited, and many features are under development. But very soon, it will be possible to make full use of these features.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
-- There are no messages in this forum --