Destructuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

Object Destructuring

In ECMAScript 5 and earlier, it would take lots of code to extract information from array and objects.

var username = {
    firstName: 'Pandiyan',
    lastName: 'Murugan'
};

var firstName = username.firstName;
var lastName = username.lastName;

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

Object destructuring syntax uses an object literal on the left side of an assignment operation.

In ECMAScript 6,

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var {firstName, lastName} = username;

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

In the above example, username.firstName is stored in firstName and username.lastName is stored in lastName.

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var { firstName, lastName, designation } = username;

console.log(firstName + ' ' + lastName + ' ' + designation);

// designation will be undefined at this point

We can set default values as follows

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var { firstName, lastName, designation = 'player' } = username;

console.log(firstName + ' ' + lastName + ' ' + designation);

// designation will be set as player if it didn't find the value for player in username object

Assigning to Different Local Variable Names

In an earlier example, we have used same in the local variable with matching the name in the object. Now let’s try to assign it to different variable as follows

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var {  lastName: localLastName, firstName: localFirstName } = username;

console.log(localFirstName +' '+ localLastName);     // MS Dhoni

Here we can use any order to assign the variables. The values will be properly set.

Array destructuring

Array destructuring syntax is very similar to object destructuring; it just uses an array literal syntax instead of object literal syntax.
The destructuring operates on positions within an array, rather than the named properties that are available in objects.

var fruits = [
    'mango',
    'banana',
    'jack fruit'
];

var [fruitOne, fruitTwo, fruitThree] = fruits;

console.log(`${fruitOne} ${fruitTwo} ${fruitThree}`);

Setting default values in an array literal is similar to object literals.

Let’s cover more ES6 features in an upcoming post. Keep reading and supporting.

Happy coding ๐Ÿ™‚

Arrow functions

I’m pretty impressed with Arrow functions in ECMAScript6. An Arrow function is very simple when compared to traditional function expressions.

Arrow functions are always anonymous and do bind its own this, arguments, super and new.target properties.

So, we can simply say Arrow functions are shorter functions and non-binding of this.

Let’s begin with exploring shorter functions.

To experiment shorter functions, we shall start creating a traditional function and then later we shall replace it with Arrow functions.

var fruits = ['mango', 'jack fruit', 'banana'];
var a = fruits.map(function (f) { return f.length });

console.log(`using traditional function ${a}`);

In the above code, I have created an array with my favorite fruits name (we call this combination of fruits as mukkani in South India which means three fruits).

Using map function, we have returned the length of each item and stored the final array in variable a. This is the traditional function expression we used to write earlier.

Now, let’s rewrite the same functionality with Arrow functions.

var fruits = ['mango', 'jack fruit', 'banana'];

// using traditional function
var a = fruits.map(function(f) { return f.length });

// using arrow function
var b = fruits.map(f => f.length);

console.log(`using traditional function ${a}`);
console.log(`using arrow function ${b}`);

In the above code, we have removed the return and the keyword function and added => between arguments and expression. We have stored the Arrow function results in variable b.

To make sure both the ways are returning the same set of results, we have written the values in the console. The console writing may look little bit different than our usual because I have used template literals in this example. Click here to know more about template literals.

Output:
using traditional function 5,10,6
using arrow function 5,10,6

 

this binding

In ES5, we will bind() or var self = this; to make functions to create their own “this”. We used to store parent this in a variable and use that during the callback.

Let create a timer with native this,

function MyTimer() {
 this.seconds = 0;
 setInterval(function() {
 this.seconds++;
 }, 1000); 
}

var myCounter= new MyTimer();
setTimeout(function() {
 console.log(myCounter.seconds);
}, 1200);

It will return the timer seconds first after that it will always return 0 (this.seconds in MyTimer function it won’t bind with this.seconds++ inside the setInterval function ).

In ES5, to bind the value we have to follow the technique of assigning the this of a parent to inside the function like follows:

function MyTimer() {
 this.seconds = 0;
 var self = this;
 setInterval(function() {
 self.seconds++;
 }, 1000); 
}

var myCounter= new MyTimer();
setTimeout(function() {
 console.log(myCounter.seconds);
}, 1200);

After using the self-variable, we can able to use the incremented value inside the setInterval function.

Let’s rewrite same in ES6,

function MyTimer() {
 this.seconds = 0;
 setInterval(() => this.seconds++, 1000);
}

var myCounter = new MyTimer();
setTimeout(() => console.log(myCounter.seconds), 1200);

The seconds variable is properly binded now.

Happy coding ๐Ÿ™‚