Skip to Content

ECMAScript 6: new opportunities

2017-05-17

In JS World, there are a lot of libraries and frameworks, but nothing happened with the language itself. And, finally, a new standard came out. In this article, I'll tell you what has a new standard prepared for the language and what advantages it has over previous versions.

The article will be useful for those who are familiar with the EC5 syntax and want to quickly master the key features of the EC6.

The content of the article:

  • Previous standards
  • Main innovations
  • Support in browsers
  • Previous Standards

    There are a lot of ECMAScript standards. The most popular of them is ECMA-262:ECMAScript 5 - the latest edition of the ECMA-262 standard (approved in 2009). Previous versions of the ECMA-262 standard were (not quite old ones):

    • ECMAScript 3. It is supported by most browsers (it was approved in 1999).
    • ECMAScript 4. This standard is not taken into account for too radical changes in comparison with the previous version of the standard. Later in July 2008, in a reduced version (but still much richer than ECMAScript 3), it resulted in a new project ECMAScript Harmony.

    Main innovations

    Here I will write about the opportunities of new specification, compare the syntax of previous versions.

    Block scope

    In the current version of JavaScript, there is a functional scope. This means that all variables declared with the keyword var will be visible anywhere in the function (even if they are declared inside the block):

    var b = 2; 
    function a() {
    b = 3;
    }
    a();
    console.log(b);/* 3 */

    The result of this code snippet in the console will be 3. Developers of other languages ​​do not understand this behavior at all in JS.

    In the new specification, the keyword let appears, which allows you to declare variables with a block scope:

    let c = 3;
    function qwe() {
      let c = 4;
    }
    qwe();
    console.log(c);/* will be SyntaxError */

    As you can see, when we try to redefine a variable that is outside the function, we get an error.

    Here I will say that in ES6 there are constants, which allow you to create immutable variables, not only visually, but also at the level of the language.

    const d = 4;
    d = 3;/* will be TypeError */

    Default parameters

    The ability to declare parameters with default values ​​was added in functions:

    function w(a=3){ 
    console.log(a)
    }
    w(5);/* 5 */
    function w(a=3) {
       console.log(a)
    }
    w();/* 3 */

    The function above is with the default value. In the first case, a variable is output, which we passed as an argument to the function. In the second case, without passing anything to the arguments of the function, the default argument value is displayed.

    Destructuring assignment

    Is a cool feature of the new standard. Allows you to conveniently extract data from objects or arrays. First, an example with an object:

    let {first: f, last: l} = {first: 'Jane', last: 'Doe'}; 
    console.log(f);/* Jane */
    console.log(l);/* Doe */

    As you can see from the examples, we get the values ​​for f and l by the keys 'Jane' and 'Doe' respectively. Similarly, destructive assignment works with arrays.

    Classes

    There were classes in the new standard. This is mainly done for the convenience of people who have switched from other programming languages. In the box, inheritance is still done through prototypes. So we can see that classes in ES6 are just syntactic sugar.

    class Person { 
     constructor(name) {
     this.name = name;
     }
     describe() {
      return 'Person called ' + this.name
    }
     }
    
     /* Subtype */
    class Employee extends Person { constructor(name, title) { super.constructor(name); this.title = title; } describe() { return super.describe() + ' (' + this.title + ')'; } }

    Arrow functions

    In ES6, the syntax of anonymous functions has become simpler. Below is an example of an arrow function, and an anonymous function with ES5 syntax:

    function SomeClass() {
     var self = this;
     self.iter = 0;
    
     setInterval(function() {
     self.iter++;
     console.log('current iteration ' + self.iter);
     }, 1000);
     }
    
     var sc = new SomeClass();  

    In ES6:

    function SomeClass() {
     this.iter = 0;>
    
     setInterval(() => {
     this.iter++;
     console.log('current iteration ' + this.iter);
     }, 1000);
     }
    
     var sc = new SomeClass();  

    The difference is that arrow function doesn’t create its own context, so this will indicate the context of the function in which the code is called.

    Template Literals

    Also a cool feature of the new standard. The main advantage is the convenient interpolation of strings. For example:

    let name = 'Jora';
    let str = `hello ${name}!`

    The result of the console work will be string 'hello Jora'.

    In the previous standard, it would look like this:

    var name = 'Jora';
    var str = 'hello ' + name;

    Symbols

    Symbols - a new primitive data type. You can use symbols to create unique identifiers for object properties or to create unique constants. For example:

    const symbol = Symbol();
    let obj = {};
    obj[symbol] = 5;
    console.log(obj[symbol]); /* 5 */

    Cycle For of

    In the old standard, methods for passing through arrays and objects (for, forEach, for-in) have already existed. Each of them has its advantages and disadvantages (for example, in forEach there is no break, continue, return, the behavior of for-in for working with arrays). Which is where the for of comes in handy. For of has a number of advantages, such as:

    1. concise and demonstrable syntax for enumeration of array elements;
    2. it has no shortcomings of for-in;
    3. Unlike forEach, it works with break, continue, return.

    Also, For of works with the majority of array-like objects, such as the NodeList lists in the DOM. Well, and a simple example of work:

    let arr = [1,2,3,4,4,12,12];
    for (var val of arr) {
     console.log(val);
    }

    The result of the console work:

    Residual parameters (...)

    In the previous standard, in order to get the Residual parameters, we used the arguments object:

    function(a, b) {
     var args = Array.prototype.slice.call(arguments, fun.length);
     return args.length;
     }
    fun(1,2,3,4,5);/* 3 */

    A shorter and convenient way to obtain the residual parameters was introduced in new standard. A similar example that counts the number of residual parameters:

    
    function doSomething(x, ...y) {
     return y.length; 
    }
    doSomething(1, 0, 0, 0);/* 3 */

    As you can see, we got the correct result, but made it much easier and shorter.

    Support in browsers

    If you really want to use ES6 in IE, you can use transpaylers (tools that rewrite the code from ES6 to ES5). The most popular of them at the moment is Babel.

Author: Ivan Trutnev

Mifort, Mifort-blog, Mifort-articles, Web Development, JavaScript, EcmaScript6