Source code of examples (GitHub)
Introduction
ECMASCRIPT 2015 aka ES 6 is the new ECMA standard standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It makes java script lovers happy 🙂 . It adds lot of goodies to java script like classes, arrow functions,block scopes , const etc.
Background
ECMASCRIPT is nothing but the standard. Almost all scripting languages including java script are created using 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 supports 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 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 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 synatx is:
// Basic syntax:
(parameters) => { statements }
(parameters) => expression
// equivalent to: => { return expression; }
Example:
[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 same as that of
[1, 2, 3, 4].map(function (x) {
return console.log(x * x);
});
2. Constants
we can declare constants using the keyword const .
Example : 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
// 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}?`);
We can also embed calculations in the string like below.
var taxPercentage = 10;
var price = 120;
console.log(`The tax is ${price*(taxPercentage/100)}`);
This will repalce the calculated value of price*(taxPercentage/100) in the string and return :
The tax is 12
And even functions too,
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 will be like below :
The total amount is ,132
4. Class
Yes, we can create class using the keyword class in java script. All java script 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 wants.
class Bake {
constructor(cake) {
this.cake = cake;
}
// Member function
getTheCake() {
console.log(`${this.cake}`);
}
}
//Declaring objects of bake class
var a = new Bake('Plum cake');
a.getTheCake();
//Assigining 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 you own flavor.
5. inheritance
Since we already got classes there should be inheritance 🙂 , yes inheritance also there in ES6 using the keyword extends
class BakeWithFlavour extends Bake{
constructor(cake,flavour){
super(cake);
this.flavour=flavour;
}
getFlavouredCake(){
console.log(`${this.cake} with ${this.flavour} flavour` );
}
}
Her BakewithFlavour class inherit from the Bake class . And its constructor calling the base constructor using super(cake).
let a = new BakeWithFlavour('Plum cake','choclate');
a.getFlavouredCake();
Here the function call getFlavouredCake() will give you a Plum cake flavored with chocolate. Enjoy your piece :).
6. Static methods
Like c# or java we can create static methods in ES6 using the keyword static. And these methods can be called using the class name itself.
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 synatx includes the key words export and import :
// 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 traspile 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 contain 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 depends on your browser and enjoy the brand new java script with ES6 standards.
Refernce
Reference 1
Reference 2
Please find the examples in GitHub here