1 minute read

ES6 new features

Below i present the most important changes which provide ES6 (ECMAScript2015).

  • Arrow function

To create function using argument and arrow symbol without braces.

// ECMAScript 6
odds  = evens.map(v => v + 1)

// ECMAScript 5
odds  = evens.map(function (v) { return v + 1; });

Source - psd2css.pl

  • let variable

let in contrast to var creates variable available only in a given block.

var b = 0; // global variable "b"
for (let a = 0; a < 10; a++) { // block variable "a"
    b += a;
}

console.log((typeof b !== 'undefined') ? b : "undefined"); // 45
console.log((typeof a !== 'undefined') ? a : "undefined"); // undefined

Source - psd2css.pl

  • const variable

Create variable like let which her value are constant.

// ECMAScript 6
const PI = 3.141593

// ECMAScript 5
Object.defineProperty(typeof global === "object" ? global : window, "PI", {
    value:        3.141593,
    enumerable:   true,
    writable:     false,
    configurable: false
})

Source - psd2css.pl

Class

They don’t change the concept of inheritance. They are just syntactic sugar for prototypal inheritance.

class Point {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    toString() {
        return '[X=' + this.x + ', Y=' + this.y + ']'
    }
}

class ColorPoint extends Point {
    static default() {
        return new ColorPoint(0, 0, 'black')
    }

    constructor(x, y, color) {
        super(x, y)
        this.color = color
    }

    toString() {
        return '[X=' + this.x + ', Y=' + this.y + ', color=' + this.color + ']'
    }
}

console.log('The first point is ' + new Point(2, 10))
console.log('The second point is ' + new ColorPoint(2, 10, 'green'))
console.log('The default color point is ' + ColorPoint.default())

Source - blog.programists.com

  • ES6 added support for modules.

Modules in ES6

Modules in ES6 are very simple to use. Like other usage of modules, ES6 provides a way to export modules so that they can be specified as dependencies to other modules. Thanks modules we can divide project to smaller parts and keep more clean and more readable project.

Exporting Modules

Export function definition:

export function setValue(x) {...}
export function getValue() {...}

Export object with the properties:

function addValues() {...}
function sumValues() {...}
function otherFunction() {...}

export { addValues, sumValues};

Importing Modules

// import all properties from values module
import * as values form './values.js';

vales.addValues();

Import specific elements from module

import {addValues, sumValues} from './values.js';

More informations: