ES6 features aka ECMAScript 2015 features in Javascript cookbook

Handy ES6 Cookbook




Javascript is evolving in a good shape in recent times. As its evolving, it brings ease of coding for the javascript developers. To make life easier for the javascript developers, ES6 features are introduced. The main ES6 features are as follows.  
  1. Arrow functions.
  2. Object Destructuring.
  3. Array Destructuring.
  4. Let, Const.
  5. Template strings.
  6. Spread Operators.
  7. Rest Operators.
  8. Optional Params.
  9. for ... of iterator.
  10. for ... in iterator.


Arrow functions

Arrow functions came with ease for JS programmers. Unless traditional functions, arrow functions provide cleaner syntax and improves code readability. For example

 ❌ Without ES6:


function isEven(num) {
  return num % 2 === 0
}


✅ With ES6:



const isEven = (num=> {
  return num % 2 === 0;
}


🌈 Refactoring:

The above function can be refactored further to 


const isEven = (num=> num % 2 === 0;


You can note that I have removed the curly braces from the above function. Because the ES6 feature allows us to remove the curly braces for single-line functions.

The above function can be even refactored to the below version


const isEven = num => num % 2 === 0;


You can even ignore parenthesis if the arrow function haves a single argument.

Object Destructuring

This feature lets us reduce some more lines of code. It is the process of extracting a property and it's the value from an object and creating a variable with the name of the extracted property and assigns the extracted value to the variable created. For example

❌ Without ES6:


const user = {
  firstName: "John",
  lastName: "Doe"
}

let firstName = user.firstName;
let lastName = user.lastName;

if (firstName === undefined || firstName === null) {
  firstName = "No firstName";
}

if (lastName === undefined || lastName === null) {
  lastName = "No lastName";
}

console.log(firstName);
console.log(lastName);


In the above snippet line no. 1 we are having an object called user that has two properties first name and last name which have some values. On the next corresponding lines, we have created a 1 + 1 variable for storing the first name and last name. And correspondingly we are checking to suppose if the first name is empty we are assigning the first name as no first name and then if the last name is empty then we are assigning it to the no last name and finally, we wrote log statement to print the results.

✅ With ES6:

We can refactor the above snippet to


let {
  firstName,
  lastName
} = user;

if (firstName === undefined) {
  firstName = "No firstName";
}

if (lastName === undefined) {
  lastName = "No lastName";
}

console.log(firstName);
console.log(lastName);


From the above snippet, we have ignored the variable assignment from code example 1 . Hence we have extracted the property and its value from an object and created a variable with the name of the extracted property, and assigned the extracted value to the variable created.

🌈 Refactoring:


let {
  firstName = "No firstName",
  lastName = "No lastName"
} = user;

console.log(firstName);
console.log(lastName);


You have noted that we have removed a significant amount of code from code 2 . If have removed the corresponding if conditions. It represents that if any targeted property is not available we can define the default value for the missing property. 

👀 Additional point: 

If you don't want the same name as a property you can even rename it with some custom name aka alias. For example


let {
  firstNamefname = "No firstName",
  lastNamelname = "No lastName"
} = user;

console.log(fname);
console.log(lname);



You can note that I took the property and assigned the alias fname and lname. 

Array Destructuring

It is similar to object destructuring but here we will use an array instead of an object.

❌ Without ES6:



let anArray = ["Apple""Banana"];

let zerothIndex = anArray[0];
let firstIndex = anArray[1];


✅ With ES6:



let [zerothIndexfirstIndex] = ["Apple""Banana"];


zerothIndex will take the 1st element of the RHS array and similarly, the first Index will take the 2nd value from the RHS array. Please note that I have used square brackets instead of curly brace which denotes it is array destructing

👀 Additional Point:

Similar to object Destructing you can use default values and aliases in array destructing 
For example


let [zerothindexfirstindexsecondindex = "orange"] = ["Apple""Banana"];


From the above example, you can see that 3rd element from the RHS array is missing so I assigned a default value with orange 


In a real-world project, we may not know the length and values of an array. Using such destructing techniques will reduce significant lines of code for sure and be even more predictable and readable.

Let, Const

In order to replace var, let & const are introduced. The only difference is let and const are block-scoped and when the variables are declared using let or const it cannot be hoisted and will not be available outside its block;

🚀 Let keyword example:

It's the same as var keyword, except its block scoped.


// its valid and value is undefined
let aVariable;

//you can change the value later
aVariable = 20;

//you can even change its datatype too
aVariable = 'Hello World!'


🚀 Const keyword example:

Const refers to "Constant". It is also a block-scoped like the "let" keyword but once when you have an assigned value you cannot change it.


const anotherVariable = 1;

// ❌ will throws an error
anotherVariable = 2

// ❌ will also throws an error
anotherVariable++; 


👀 Additional Point:

You should assign some values to constant while declaring otherwise it will throw an error.


// will throws an error,
// because you need to assign some value while declaring constant
const aVariable;





//  this is the correct approach
const aVariable = 20;


Template Strings

Template strings let you the string concatenation with ease. For example,

❌ Without ES6:


const user = {
    firstName:"John",
    lastName:"Doe",
    age:25
}
let aString = "Hello " + user.firstName + " " 
user.lastName + ", your age is " + user.age + "."

console.log(aString)
// Hello John Doe, your age is 25.

 

✅ With ES6:

It provides us a cleaner syntax enclosed using the backtick character ` (left to 1 in keyboard) and variables can be identified inside ${...}.


const user = {
    firstName:"John",
    lastName:"Doe",
    age:25
}
let aString = `Hello ${user.firstName} ${user.lastName}, your age is ${age}.`

console.log(aString)
// Hello John Doe, your age is 25.


👀 Additional Point:

You can use even javascript expressions inside ${...}.  You can even write multiline strings using it.

For Example:
You can note that I have used the a+b inside ${...}. And I have added multi-line string using backtick character.



let a = 1b = 2;

// 🎁 Expressions inside ${...} example.

let result = `Sum of ${a} + ${b} is ${a + b}`;

console.log(result);
// Sum of 1 + 2 is 3.


// 🎁 Multiline string example
let greetings = `
Hello good morning,
Have a nice day.
How's going on?
`;

Optional Params aka Default Params

Optional params let you take the default value for the parameter which are missing while being called.

❌ Without ES6:

For the below example, I have written an if condition to check whether the discount is falsy. If "yes" this function will consider discount as "0". 


// this will subtract discount from the total
// objective:
// Discount amount should be 0 if no discount  
function getAmount(totaldiscount) {
  if (!discount) {
    discount = 0;
  }
  return total - discount;
}


✅ With ES6:

You can note, I have assigned the discount as 0 in the arguments area. This means the discount will be 0 when no second parameter is passed to this function.

 
function getAmount(totaldiscount = 0) {
  return total - discount;
}

// without discount
// now discount is 0
console.log(getAmount(120)); // 120

// with discount
// now discount is 20
console.log(getAmount(120,20)); // 100


👀 Additional Point:

You can even use optional params in arrow functions too.


const getAmount = (totaldiscount = 0=> total - discount;

// without discount
// now discount is 0
console.log(getAmount(120)); // 120

// with discount
// now discount is 20
console.log(getAmount(12020)); // 100


For .. of iterator

Unlike traditional "for" loops. "For of" doesn't take huge arguments. Arrays, strings can be used for the iteration using the "for of" loop. For an example

❌ Without ES6:

The below example will print Hello World in a vertical pattern. You can note that we have added more operations like (let i = 0i < singles.lengthi++) , which increases the space complexity and code size.


let singles = [123456];
let doubles = [];

for (let i = 0i < singles.lengthi++) {
  doubles.push(singles[i] * 2);
}

console.log(doubles);
// will print [2,4,6,8,10,12]


✅ With ES6:

The below examples are much simpler, cleaner, and easier to understand than the previous one.

Example 1 (using Array):


let singles = [123456];
let doubles = [];

for (let element of singles) {
  doubles.push(element * 2);
}

console.log(doubles);
// will print [2,4,6,8,10,12]


Example 2 (using String):

You can even use string for the iteration. 


let str = "Hello World";
for(let letter of str) {
  console.log(letter)
}
// this will also print Hello World in vertical align
// H
// e
// l
// l
// o
// .
// .
// .
// l
// d


For .. in iterator

For in loop lets you iterate over keys in an object

❌ Without ES6: 

The below example will print keys and values.


const user = {
  firstName: "John",
  lastName: "Doe",
  age: 25
}

Object.keys(user).forEach(key => {
  console.log(`
    KEY: ${key}
    VALUE: ${user[key]}

  `);
});

// Output:

// KEY: firstName
// VALUE: John

// KEY: lastName
// VALUE: Doe

// KEY: age
// VALUE: 15


✅ With ES6:

Same example with ES6

let user = {
  firstName: "John",
  lastName: "Doe",
  age: 25
}

for (const key in user) {
  console.log(`
    KEY: ${key}
    VALUE: ${user[key]}

  `);
}

// Output:

// KEY: firstName
// VALUE: John

// KEY: lastName
// VALUE: Doe

// KEY: age
// VALUE: 15


Spread Operator

Spread operator (...) in simple terms, it helps you to take out the [] for array and {} for object and expand the object or array with commas so that you can concat or place between the elements of objects or array correspondingly.

🚀 Example 1:

The below example illustrates how to merge 2 arrays and pushing an array to an array.


// Merging 2 or more arrays
let array1 = ["A""B""C"];
let array2 = ["D""E""F"];

let combinedArray = [...array1, ...array2];
console.log(combinedArray);
// ["A", "B", "C", "D", "E", "F"]


combinedArray.push(
  ...["G""H""I"],
  ...["J""K""L"]
)
console.log(combinedArray);
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]


🚀 Example 2:

The below example will merge all the objects such as user, account, and medical information into a single object called userData.


let user = {
  id: 342,
  firstName: "John",
  lastName: "Doe",
  age: 25
}

let accountInfo = {
  cardName: "Master Card",
  cardNumber: "765432189012",
  cvv: "123"
}

let userMedicalData = {
  history: [
    {
      name: "Medical Diagnosis",
      amount: 12000,
      at: "2021-07-15T10:09:21.918Z"
    },

    {
      name: "Treatment",
      amount: 45000,
      at: "2021-07-20T10:09:21.918Z"
    }
  ]
}

// merging all objects using spread operator

let userData = {
  ...user,
  ...accountInfo,
  ...userMedicalData
};

console.log(userData);

/*
{
  "id": 342,
  "firstName": "John",
  "lastName": "Doe",
  "age": 25,
  "cardName": "Master Card",
  "cardNumber": "765432189012",
  "cvv": "123",
  "history": [
      {
          "name": "Medical Diagnosis",
          "amount": 12000,
          "at": "2021-07-15T10:09:21.918Z"
      },
      {
          "name": "Treatment",
          "amount": 45000,
          "at": "2021-07-20T10:09:21.918Z"
      }
  ]
}
*/


Rest Operator

The rest operators allow an indefinite no. of arguments to the function as an array. In other words, if we do not have any idea how many arguments are required to pass, we have an option called Rest. For example,

✅ With ES6:


function addAll(...numbers) {
  // now numbers will be an array
  // have indefinite no. of arguments.
  let sum = 0;
  for (let i = 0i < numbers.lengthi++) {
    sum += numbers[i];
  }

  return sum;
}

// I am passing 2 params
addAll(12// 3

// I am passing 3 params
addAll(124// 7

// I am passing indefinite params
addAll(124532345234// 38


Array Methods

Array methods help in manipulating, evaluating the arrays. It helps to reduce the significant lines of code from your program. Also, it provides more readability and understandability of code.

If you want the array method cookbook click here.


 🎉 Thanks for reading this article. I am very happy that you spent your time on something good. I hope this article gave you a clear idea of ES6 features. Please comment and share this article with someone who really needs this. Thanks again and stay connected for more interesting posts.

7 Comments

  1. Hanndy post for people preparing for interviews.
    Good one Abdul!

    ReplyDelete
    Replies
    1. That was the huge encouragement from you 🎉. Keep motivating me. Thanks for your support Sushmitha 🙏

      Delete
    2. Reply here if you need anything as next post 🎉

      Delete
  2. Those comparisons will help in optimisation of code .
    Thank you 😊

    ReplyDelete
    Replies
    1. Thanks a lot Anusha and thanks for your support. Reply here if you need anything as the next post.

      Delete
  3. Nice content bro. Keep updating the new contents and technologies. Good work.

    ReplyDelete
    Replies
    1. Thanks a lot Ashok 🎉. This kind of motivation I really need from you and everyone 🙂

      Delete
Previous Post Next Post