An introduction to ES6

Spread the love

ES6 also know as ECMAScript 2015 and JavaScript 6 is the 6th major release of the ECMAScript language specification.

ECMAScript is a Standard for scripting languages and JavaScript is the most popular implementation of the ECMAScript Standard. ES6 introduces some new features which makes programming in JavaScript better.

Browser Compatibility

Most of ES6 features can be used latest version of all browsers, for browsers without support, you can use this ployfill. You can also see which features are supported on which browsers using this handy table.

ES6 Features

Some of the new features of ES6 are:

Variable declaration

You can not declare variables with the keywords let and const

let disallows you from re-declaring the variable with the same name, let also is scoped to the nearest enclosing block

example:

function loopThroughUsers() {
    //user is undefined here

    for( let user = 0; user < 5; user++ ) {
        //user is only visible in within this for loop
    }
    //user is undefined here
}

For const variable, the variable can be declared only once and the value cannot be changed.

Default Parameters

In ES6, functions can have parameters with default value

function doSomething(type, task=’start’){}

In the above line, the task parameter has a default value.

Exponentiation Operator

You can use the exponential operator **  to raise the first operand to the power of the second operand.

let a = a ** a; // a**a = a^2

Arrow functions

Arrow functions lets you write small functions more concisely.

In ES5 Javascript:

var doSomething = function(task){
return performTask(task);
}

  

In ES6

let doSomething = task => performTask(task);

As you can see from the above code snippets, arrow functions allow you to write functions, without the function keywork, without the  curly braces (), and without the return keyword.

Promises

I have written a blog post about promises, which you can find here.

Template Literals

Template Literals is a way to output a variable’s value in a string.

In ES5, you would need to do something like

var a = 4;
var b = 72;
var output = "the sum of"+a+" and "+b+" is"+(a+b);

In ES6, you can use ${variable_name} inside a backtick ` string

example: “

let a = 4;
let b = 72;
let output = `the sum of ${a} and ${b} is ${a+b}`

Destructuring Assignment

if you have an object  or array and you want to assign some variables to specific fields in the array or object, you can use destructing assignment to automagically assign variables which have the same names as the key.

For example

{name, age} = {age:25, name:"Test"};

In the above example, the name variable, get the value of the name “Test” of the object, and age is 25

ES6 has many, many more features like classes,  modules, new datatypes like Set, etc. You can find a large list of features here.