ES6 Features

Topics we will cover in this blog:

  • Array Destructuring
  • Object destructuring
  • Concatenate Arrays and object
  • Template strings

Array Destructuring

The destructuring assignment allows reading values from an array or properties from an object, into distinct variables. Array destructuring is a new feature in ES6, which makes code easier to read. Lets look at example without array destructuring.

code-a.png

Lets look how above code can be made simple to read and with less number of lines using array destructuring

code-b.png

There is no need to declare variables separately. The first index value of employeeDetails array will be assigned to first index variable firstName and second index value of employeeDetails array will be assigned to second index variable lastName in array destructuring. You can identify array destructuring when you see a array on left side of = operator and variable name on right side.

Object destructuring

Similarly to array destructuring , you can destructuring an object also. lets look at an object without destructuring first.

code-c.png

Lets look how to refactor above code using object destructuring.

code-d.png

For object destructuring variable name should match with keys of the object.

You can assign default value to object being destructured even though if the property is not present in object.

code-e.png

If there is property in object, it will ignore the default value and takes in account of value in object.

code-f.png

Renaming of variable is also possible while destructuring.

code-g.png

Concatenate Arrays and object using (...)Spread notation

Spread syntax expands an array into separate elements .We can merge or combine array together using …spread operator

spread-1.png

Similarly you can combine objects also using …spread operator

spread-2.png

Since place is common in both person1 and person2 object , totalPerson will contain unique properties from both object and common properties from object present at last in totalPerson.

Template strings

Template strings allow embedding expressions.Single or double strings do not support interpolation and are restricted to one line. Template strings solve this problem.

template-1.png

Template string are written inside backtick (`) character Template string can be multiline string , which is not possible using single and double quotes.

template-2.png

Another feature of template string is interpolation , which means we can write javascript variable in it and it will give value of variable where it is called. They contain placeholder indicated by dollar($) and followed by curly brackets({ }) inside template string as shown below.

template-3.png