Destructuring and parameter handling in ECMAScript 6

Destructuring and parameter handling in ECMAScript 6

Written by Amine Dev on Jan 13th, 2019 Views Report Post

When using JavaScript we make a lot of use of objects and tables. It also often happens that you need some information from an object or array in variables. We can obviously do it with ES5, but we will see in this chapter that ES6 offers us a very practical tool: the destructuration.

Destructuring  an object

You have an object and you want to extract its data. With ES5 you proceed as follows:

var person = { name: 'Durand', adress: 'Usa' };
var name =person.name;
var adress = person.adress;
console.log(name);  // Durand
console.log(adress);  // Usa

We have a simple code but it could quickly get heavier with a complex or loaded object.

With ES6 you can use this syntax:

let person = { name: 'Durand', adress: 'Usa' };
let {name, adress} = person;
console.log(name);  // Durand
console.log(adress);  // Usa

Alias

To avoid name conflicts you can assign aliases:

let exemple = { 
  person: { name: 'Durand', adress: 'Usa' },
  age: 20
};
let { person: { name: personName, adress: personAdress }, age: personAge } = exemple;
console.log(personName)  // Durand
console.log(personAdress)  // usa
console.log(personAge)  // 20

Default value

The behavior is exactly the same as when using the extraction of a property of an object with the classical syntax, the value is undefined:


let person = {name: 'Durand', adress: 'Usa'};
let { name,adress, age } = person;
console.log(name)  // Durand
console.log(adress)  // Usa
console.log(age)  // undefined

But you can provide a default value:

let person = {name: 'Durand',adress: 'Usa'};
let { name, adress, age = 20 } = person;
console.log(name)  // Durand
console.log(adress)  // usa
console.log(age)  // 20

Let's deconstruct a array


let persons = [ 'Pierre', 'Jacques', 'Paul' ];
let [one,two, three ] =persons;
console.log(one); // Pierre
console.log(two); // Jacques
console.log(three); // Paul

With a table we have to choose names for the variables since at the base we just have indexes.

But nothing prevents us from declaring the variables before:

let name = [ 'Pierre', 'Jony'];
let one = 'Paul';
let two = 'Martin';
[ one, two ] = name;
console.log(one); // Pierre
console.log(two); // Jony

We can recover a limited number of elements if we want:


let name = [ 'Pierre', 'Jony', 'Paul' ];
let [ one,two] = name;
console.log(one); // Pierre
console.log(two); // Jony

Comments (0)