ES6 features — A walk through

Aravind S
6 min readJun 22, 2018

--

We are going to discuss few ES6 features which we can use while coding.

Template Literals

The below code shows what is template literals in ES6 compared to ES5

/*IN ES5*/
var name = 'Hello World';
var message = 'Hey' + name + ',';
/*IN ES6*/
let name = 'Hello World';
let message = `Hey ${name},`;

We are using backtick character here. To add a placeholder in a template literal, we use the ${expression} syntax. You can replace “expression” with any JavaScript expressions. Another benefit of using template literals is that they can expand multiple lines.

let name = 'Hello World';
let message = `
Hi ${name},

Thank you for your Clap.

Happy learning,
Aravind
`;

Let and Const

we used the var keyword to define variables in ES5. The scope the var keyword is the entire enclosing function. Here’s an example:

function helloworld() {
for (var x = 0; x < 2; x++) {
// x should only be scoped to
this block because this is where we have
defined x.
}

// But it turns out that x is available here as well!
console.log(x); // 2
}

Another issue with the var keyword is that if you use it at the top level outside of a function, it creates a property on the global object. ES6 introduced 2 new keywords for resolving these issues: let and const. Both these keywords define variables that are scoped to the containing “block” not “function”:

function helloworld() {
for (let x = 0; x < 2; x++) {
// With the "let" keyword, now x is only
accessible in this block.
}

// x is out of the scope here
console.log(x); // x is not defined
}

With const we can define a constant. So we cannot reassign it later:

const x = 1; 
x = 2; // throws "Assignment to constant variable."

Also let and const don’t create a property on the global object if you use them at the top level:

Arrow Function

Here’s a function expression in ES5:

const add = function(num) { 
return num + num;
}

With arrow functions, we get rid of the function keyword and put a fat arrow (=>) between the parameters and the body of the function:

const add = (num) => { 
return num + num;
}

If our function is a one-liner and returns a value, we can drop the return keyword as well as the curly braces:

const add = (num) => num + num;

If our arrow function includes only a single parameter, we can even drop the parenthesis:

const add = num => num + num;

If our arrow function doesn’t have any parameters, then

const helloWorld = () => { console.log('Hello World'); };

Arrow functions are particularly useful when you need to pass callback functions as arguments:

// ES5
var activeJobs = fruitsArray.filter(function(fruit) {
return fruit;
});

// ES6
const activeJobs = fruitsArray.filter(fruit=> fruit);

Arrow functions, unlike normal functions, don’t rebind this.

// ES5
function onSubmit() {
// Keep a reference to "this" so
we can use it in the inner function below.
var that = this;
orderService(order, function(result) {
// In JavaScript, ever function defines
its own "this" value. So, "this" in this
inner function here is different from "this"
in the onSubmit() function. That's why we had to keep a
reference to "this" and store it in "that". Now,
we can use "that":

that.result = result;
});
}

Arrow functions use the this value of the enclosing execution context. So, if we replace the inner function above with an arrow function, we don’t need to keep a reference to this anymore.

// ES6
function onSubmit() {
orderService.store(order, result => {
// Since we're using an arrow function here,
"this" references the "this" value of the
containing function (onSubmit). Arrow functions
don't re-define "this".
this.result = result;
});
}

Destructuring

Destructuring is an expression that allows us to extract properties from an object, or items from an array. Let’s say we have an address object like this:

const address = { 
street: 'Pallimon',
city: 'Kollam',
state: 'Kerala'
};

Now, somewhere else we need to access these properties and store their values in a bunch of variables: here is both ES5 and ES6 versions

//ES5
var street = address.street;
var city = address.city;
var state = address.state;
//ES6
const { street, city, state } = address;

We can also destructure arrays but we use square brackets ([]) instead of curly braces ({}).

//ES5
var values = ['Hello', 'World'];
var first = values[0];
var last = values[1];
//ES6
const values = ['Hello', 'World'];
const [first, last] = values;

Default Parameters

In ES5, if any of the function parameter don’t have a value means we will be checking whether its undefined and assign some default value.This can be done easily in ES6 as below:

//ES5
function getUser (name, year) {
year = (typeof year !== ‘undefined’) ? year : 2018;
// remainder of the function…
}
//ES6
function getUser (name, year = 2018) {
// function body here...
}

Import and Export

export allows you to export a module to be used in another JavaScript component. We use import to import that module to use it in our component.

If we want to export a single value or to have a fallback value for our module, we could use a default export:

// MyClass.js
class MyClass{
constructor() {}
}
export default MyClass;

// Main.js
import MyClass from 'MyClass';

default export is only one per module.In the case of named export, we have to write like:

// lib.js
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}

// main.js
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

// or you can call them with '*'
// but then you have to prefix the exports with
// the module name

import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5

Promises

Promises are a new feature of ES6. It’s a method to write asynchronous code. It can be used when, we want to fetch data from an API, or when we have a function that takes time to be executed. Promises make it easier to solve the problem, so let’s create our first Promise!

let p = new Promise(function(resolve, reject) {      
if (/* condition */) {
resolve(/* value */);
// fulfilled successfully
}else {
reject(/* reason */);
// error, rejected
} });

The Promise takes two parameters: resolve and reject to handle an expected error.To consume the Promise — meaning we want to process the Promises value once fulfilled — we attach a handler to the Promise using it’s .then() method. This method takes a function that will be passed the resolved value of the Promise once it is fulfilled.

var p = new Promise((resolve, reject) => resolve(10)); 
p.then((val) => console.log("fulfilled:", val)) //10
.catch((err) => console.log("rejected:", err));

Note: the fetch function returns a Promise itself!

const url='https://jsonplaceholder.typicode.com/posts';const getData=(url)=>{
return fetch(url);
}
getData(url).
then(data=> data.json()).
then(result=> console.log(result));

Rest parameter and Spread operator

spread operator spread the elements of array into individual values.

function getSum(x, y, z){
console.log(x+y+z);
}
let sumArray = [10,20,30];
getSum(...sumArray);

We have put ... in front of array, so it spread the elements of array into individual values. It allows to split an array to single arguments which are passed to the function as separate arguments.

Now, let’s concatenate two arrays:

var a = [1, 2];
var b = [3, 4];
var c = [...a,...b]
console.log(c);

Output would be [1, 2, 3, 4];

Now, let’s look at the rest operator.

As the name suggests, Rest operator will take care of the rest of the parameters. Here is a snippet:

function numbers(x, y, ...z){
console.log(x, y, z);
}
numbers(1, 2, 3, 4, 5, 6);

The output of above code would be 1 2 [3, 4, 5, 6].

As you can see the x and y have been assigned the values 1 and 2 respectively whereas rest of the parameters got assigned to z. Rest parameters are indicated by three dots preceding a parameter. Named parameter becomes an array which contain the rest of the parameters.

Remember: It’s the same three dots …, the how and where of use, makes these three dots Spread or Rest.

Classes

Classes are the core of object oriented programming (OOP). They make your code more secure and encapsulated. Using classes gives your code a nice structure and keeps it oriented.

class myClass{
constructor(name,age){
this.name=name;
this.age=age;
}
}
const Home= new myClass("said",20);
console.log(Home.name)// said

More about classes can be referred here MDN classes

Thanks to Mosh and Other medium articles for making me understand all this :D

Happy Reading!

--

--

Responses (3)