Basic ES6 Features
Arrow Functions: Before moving to arrow functions, let’s check once how normal functions defined:
const array = [ 1, 2, 3, 4];
let y = 0;
const sum = array.reduce(function (x) { y += x; return y; })
This is a Traditional function expression. Let’s have a look to arrow function:
const sum = array.reduce(x => x+= x;);
Here, you can see arrow functions are less verbose than traditional function expressions.
let and const: let
works similarly to var
, but the variable it declares is block-scoped, it only exists within the current block. var
is function-scoped and const
works like let
, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards. You can go through with the article to know more in detail.
Template Literals: Template literals or interpolation in other languages is a way to output variables in the string. So in ES5 we had to break the string like this:
let first = "soni", last = "pandey", name = 'Your name is ' + first + ' ' + last + '.'
In ES6, we can use a new syntax ${first} ${last}
inside of the back-ticked string:
let first = "soni", last = "pandey", name = `Your name is ${first} ${last}.`
Multi-line Strings: Previously in javascript, we had to use one of these approaches:
var data = 'The other new keyword for\n\t'
+ 'variable declaration in ES6 is const\n\t'
+ 'but it is often misinterpreted as being a,\n\t'
+ 'constant value\n\t'
var data = 'You have the right to be you.\n\
You can only be you when you do your best.'
While in ES6, simply utilize the backticks:
var data = `The other new keyword for
variable declaration in ES6 is const
but it is often misinterpreted as being a,
constant value`
Modules: There were no native modules support in JavaScript before ES6. May be some was prefered CommonJs, requireJS etc. I used CommonJs. Suppose, we have to access one variable result and one function createUser outside the file. So, here is the code in CommonJs:
/** save this file with the name of index.js*/
module.exports = {
result: success,
createUser: function() {
...
...
}
}/** How to access result variable and createUser function outside of index.js file.*/
var Index = require('index.js')
console.log(Index.result) // success
In ES6, we would use export
and import
. For example, this is our library in the ES6 index.js
file:
export var result= success
export function createUser(data) {
...
}
In the importer ES6 file main.js
, we use import {name} from 'my-module'
syntax. For example,
import {result, createUser} from 'module'
console.log(result) // success
I am just exploring in Es6, and found these all things are very easy and we can smoothly move from Es5 to Es6 for using basic features of Es6.
You can reach out to me for any doubt and suggestions. Please share this with others as well.
Oh, and if you like this, click the 💚 below. Keep watching this space and follow me for more articles on technology.
Thanks!
Happy Coding!!