Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Introduction to ECMASCRIPT 2015 - ES6

4.64/5 (7 votes)
2 Nov 2015CPOL3 min read 18.9K   79  
An overview of the brand new ECMASCRIPT 2015(ES6)

Introduction

ECMASCRIPT 2015 aka ES 6 is the new ECMA standard standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It makes JavaScript lovers happy :). It adds lot of goodies to JavaScript like classes, arrow functions, block scopes, const, etc.

Background

ECMASCRIPT is nothing but the standards. Almost all scripting languages including JavaScript are created ES (ES is using across this article for ECMASCRIPT) as core.

Wiki link for history.

Browser Support

None of the browsers fully support ES 6. EDGE 13 suports 80% of ES 6 features and FF43 supports 72%. You can check the complete list of browsers which support ES 6 here.

To overcome the browser support issue (only for the time being), we can use transpilers to convert the ES6 code to ES5 and use them in your page. I am using babel transpiler in my examples to convert my ES6 code to ES5. There are many transpilers available. Have a look here.

What is New in ES6?

I would like to introduce some new goodies in ES 6 with examples in JavaScript.

1. Arrow Functions

ES6 has arrow functions which has a shorter syntax compared to normal function using the => syntax and are anonymous. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. The syntax is:

JavaScript
// Basic syntax:
(parameters) => { statements }
(parameters) => expression
// equivalent to:  => { return expression; }

In the example:

JavaScript
[1,2,3,4].map(x=>console.log(x*x));

This will return squares of the given list of integer array. And the result is the same as that of:

JavaScript
[1, 2, 3, 4].map(function (x) {
  return console.log(x * x);
});

The transpiled code should look like this:

2. Constants

We can declare constants using the keyword const.

JavaScript
Eg: const pi=3.14;

3. Template Strings

The beauty of string templates like String.Format() in C# is available in ES6. A tag can be added to create customized strings. Also, it is possible to create multi line string without using '\n'.

Use back ticks (`) defining template strings. The sample code contains different ways of implementation:

JavaScript
// Multi line strings
var multilineString =`In JavaScript this is
 not legal.`
console.log(multilineString);
 
// String interpolation
var name = "Bob", time = "today";
console.log(`Hello ${name}, how are you ${time}?`);
JavaScript
//Embedding calculations in string. 
var taxPercentage = 10;
var price = 120;
console.log(`The tax is ${price*(taxPercentage/100)}`);

This will replace the calculated value of price*(taxPercentage/100) in the string and return:

The tax is 12
JavaScript
function calculateTotal(str,amt){
var taxPercentage = 10;
return str+(amt+(amt*(taxPercentage/100)));
}
var amt=120;
var msgWithTax= calculateTotal `The total amount is ${amt}`
console.log(msgWithTax);

This will create a string by calling the calculateTotal function and replaces the tag with calculated value and the result should be like:

The total amount is ,132

4. Class

Yes, we can create class using the keyword class in JavaScript. All JavaScript lovers are happy to know js is now object oriented. :)

In the example below, I am creating a class with name Bake which has a constructor which accepts a cake type. The class has a member function named getTheCake which gives you the cake you want.

JavaScript
class Bake {
constructor(cake) {
this.cake = cake;
}
getTheCake() {
console.log(`${this.cake}`);
}
}
//Declaring objects of bake class
var a = new Bake('Plum cake');
a.getTheCake();
//Assigning the variable.
a.cake='Choclate cake';
a.getTheCake();

Here, the first function call gives you a plum cake and the second gives you a Choclate cake. Enjoy the cake or create your own flavor.

5. Inheritance

Since we already got classes there should be inheritance :), yes inheritance also there in ES6 using the keyword extends.

JavaScript
class BakeWithFlavour extends Bake{
constructor(cake,flavour){
super(cake);
this.flavour=flavour;
}
getFlavouredCake(){
console.log(`${this.cake} with ${this.flavour} flavour` );
}
}

Her BakewithFlavour class inherits from the Bake class. And its constructor calling the base constructor using super(cake).

JavaScript
var a = new BakeWithFlavour('Plum cake','choclate');
a.getFlavouredCake();

Here, the function call getFlavouredCake() will give you a Plum cake flavored with choclate. Enjoy your piece :).

6. Static Methods

Like C# or Java, we can create static methods in ES6 using the keyword static. And this method can be called using the class name itself.

JavaScript
class Bake {
  static getPlumCake(){
     return 'Plum cake';
  }
} 

console.log(Bake.getPlumCake());

7. Modules

ES 6 supports modules for component definition which is to support the standards of both common js modules and AMD (Asynchronous Module Definition - The most popular implementation of this standard is RequireJS). The syntax includes the keywords export and import:

JavaScript
// module.js 
   
export function square (list[]) {
    list.map(x=>console.log(x*x));
}
    
//------ main.js ------
import {square} from 'Module';
// or you can use import  * from 'module' to import all the members in module
var list=[1,2,3,4,5];
square(list);

If we transpile this code using babel, we need common.js implementation. Because bable is using the common.js module model to transpile the code.

In examples, it contains both ES6 file as well as the transpiled file. I have used the transpiled js files in all. Try to use the actual ES 6 js files depending on your browser and enjoy the brand new JavaScript with ES6 standards.

References

License

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