Destructuring and parameter handling in ECMAScript 6

Updated Feb 27, 2019・1 minute read Post By Amine Dev
Destructuring and parameter handling in ECMAScript 6

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;
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


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

© 2020 DevDojo LLC. All rights reserved.