ECMAScript 2016 also known as ES6 has added many exciting features in the javascript developer toolbox. Released in June 2015, ES6 is the successor of ES5 which was released in December 2009.
ES6 specially added many shortcuts to make it, even more, user-friendly. It added lots of missing features all modern developer needs in a modern programming language.
Here we will enlist top 10 must know features of ES6.
1. Default Parameters
Default parameters allow us to specify default values for a given function if the argument value is not specified. In other modern languages default parameters were common in practice. This feature was not available in JS till ES6. Before this developers have to specify the default values with some sorts of hacks such as logical OR operator. With ES6 you can set default params as in any other programming languages.
Before ES6:
function add(x,y){ var a=x||5; var b=y||10; return a+b; }
After ES6: function add(x=5,y=10){ return x+y; }
2. String Interpolation
String interpolation allows you to insert the JS variable directly inside a string declaration.
String interpolations also known as Template literals made working with strings much more fun. Now we can truly implement string.format() like functionality in other programming languages in JS itself. Before ES6 you had to perform messy string concatenation to generate the desired string with JS variables. ES6 made it really simple and fun . with use of back tilt (`) and ${} operators we can easily perform string interpolation.
Before ES6:
var username="Sabin"; var day="Sunday"; var greeting = "Hello " +username+" Today is "+day;
After ES6:
var greeting = `Hello ${username} Today is ${day}`
3. Arrow Functions
Arrow functions (commonly used as lambda in other languages) enhances the readability by providing clean syntactic sugar to bulky functional statements. Furthermore, arrow functions in JS make working on multiple contexts far more easier. Unlike function() which overrides the global scope (ie. this) arrow function won’t get mutated making it breeze to work with code involving “this”.
Arrow function has 2 major benefits:
1. It simplifies your code syntax
2. It prevents this from changing
As it doesn’t change, the global scope its really handy to use with
Before ES6: //store the public context var _this = this; $('.button').click(function(event){ //perform the action on public context _this.doSomething(); });
It also makes it easy to create inline functions with an implicit return
var timesTwo = number => number*2; var multiply = (x, y) => x*y; multiply(2,3) timesTwo(8)
Because of its lightweightness and clean structure, it’s really great to use the arrow function as an anonymous function. As it doesn’t affect the parent scope working in the huge application is really a breeze.
4. True Classes
ES6 finally brought true Object-oriented class design in JS making it familiar for many Java/C# developers out there. using new class and constructor keyword we can create traditional style class in JS. We can also extend one class by another using extends keyword. This extension made js looks more like other modern oop languages. Developers coming to JS from another background would find this structure very handy.
class Book{ constructor(title,author){ this.title=title; this.author=author; } function getName(){ return this.title } } class Series extends Book{ constructor(title,author,genre) { super(title,author); } function getGenre() { return this.genre; } }
let series= new Series ('The song of Ice and Fire', 'GRR Martin', 'Fantasy'); console.log(series.getName());
5. Block Scope for Let and Const
ES6 added the scopes to the blocks so whenever you declare the variables its scope will be different based on its scope. Before ES6 blocks didn’t do anything to the scope of a variable. var made everything of global scope .let and const did not just let users declare variables, it added block scopes making it more powerful than var. its like var with scope. const is immutable constant but as it is scoped, we can reuse it multiple times in code blocks without interference.
Before ES6:
function getAge(){ var age=20 { var age=30 } { var age="twenty"; } return age; } //returns twenty
After ES6:
function getAge(){ let age = 20; { let age = 30; } { let age= "twenty" } return age; } console.log(getAge()); //returns 20
In ES6 function getAge returns 20 because it’s the only one with global scope inside the function.
6. Destructuring objects
Destructuring makes it really easy to pull variables and their values from objects and arrays. Before ES6 we must have to provide the name of the object and variable each time we have to create a new variable. with ES6 we can parse many keys from just a single line of code.
Before ES6: var details={age:20,name:"ram"} var age=details.age var name=details.name
After ES6:
var details={age:20,name:"ram"} var {name,age}=details
In ES6 name and age would be auto-filled from details object.
7. Promises
Although increasing some line of code Promises provide a great way to manage your asynchronous function calls. Each promise holds 2 objects resolve and rejects which fires as per the result of your async calls. Also managing asynchronous callback is a lot easier.
Before ES6:
setTimeout(functon(){ console.log('Timeout's up!'); }, 1000);
After ES6:
var promise= new Promise((resolve, reject) => { console.log('Might be successful'); resolve();//reject }).then(() => { console.log('Doing something else...'); })
8.Array Functions
Although not compulsory array functions make it really easier to work with arrays. As most of the JS code involves working with array and objects array functions help you save lots of time and codes.
forEach: it allows looping across array elements really easy and fun.
instead of for x in y, we can use y.forEach(x=>{});
let numbers=[1,2,3,4,5] numbers.forEach(num=>{ console.log(num*2); });
map: when we have to do some operations in an array element and return new array we can use the map function.
var numbers = [1, 2, 3, 4, 5]; let numbers_twice=numbers.map(x=>x*2);
filter: Filter function makes it a lot easier to filter array elements and create a new array. For example, if we have to filter even numbers only from the list of numbers we can write the following code.
var numbers = [1, 2, 3, 4, 5]; //exclude all events and return odd only var odds=numbers.filter(x=>{return x%2});
9. Modules in ES6
Importing modules is really easy with ES6 with improved import operators.
–result.js
export var id= 10; export function getResult() { };
we can import both of them using,
import {id, getResult} from 'result';
It’s really handy when it comes on importing multiple modules from the same file.
10. Spread Operator …
Spread operator makes it really easier to destructure array into single arguments to be passed into the function as separate arguments.
function sum(a,b,c){ return a+b+c } let numbers=[1,2,3] console.log(sum(...numbers)); //returns 6
With ES5 we need to do something like,
function sum(a, b, c) { return a + b + c; } var numbers= [1, 2, 3]; console.log(sum.apply(undefined, numbers)); // 6
This function also works in reverse for creating parameterized arrays.
function sum(...numbers){ let sum=0; numbers.forEach(x=>sum+=x); return sum; }
Now we can create sum function with any number of input arguments.
sum(1,2,3); sum(1,2,3,4,5,6);
Bonus: Object Literals
Although not so huge change, new object literal syntax will save some of our time and improves the readability of our code. Previously we have to return from a method as an object of key-value pair, now JS automatically associates the value with the variable name.
Before ES6:
function getInfo(name,age,gender){ return{ name:name, age:age, sex:gender } }
After ES6:
function getInfo(name,age,gender){ return {name,age,gender} }
Although it’s not so huge change it’ll save you some time.
These are the most important and must know ES6 features for every JS developer. Furthermore, ES8 is also released with some more exciting features. We’ll cover them in our next posts. Which feature did you like the most? please let us know in the comment section below. Thank You.