Destructuring in ES6

Destructuring in ES6

Destructuring is a cool new feature in ES6 which allows you to easily extract values from an object or an array.

On Arrays

let numbers = [1, 2, 3, 4, 5]; 
let [a, b] = numbers; // a => 1, b => 2

Array items are set by position, therefore when destructuring an array, skipping a variable (with an additional comma) will result to taking the next item from the array in the position set in the array. Example:

let numbers = [1, 2, 3, 4, 5]; 
let [a,b, ,d] = numbers // a => 1, b => 2, d => 4 - You can skip some values from the array by using a blank with a comma. The position is therefore important in array destructuring.

We can also define default values to the parameters in the destructured array. Example:

let numbers = [1, 2]; 
let [a, b, c = 3] = numbers; // a => 1, b => 2, c = 3

Then if the numbers array is changed, and a value is set to the third item in the array, this third item value will be used instead of the default one. Example:

let numbers = [1, 2, 5]; 
let [a, b, c = 3] = numbers; // a => 1, b => 2, c = 5

A simple case study is: To swap values of 2 variables:

let a = 8, b = 6;
[a, b] = [b, a];
console.log(a,b) => 6, 8

Destructing and Rest on arrays

In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array.

The result is similar to Array.prototype.slice(), as shown below:

const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b);
console.log(arr);

The console would display the values 1, 2 and [3, 4, 5, 7].

Variables a and b take the first and second values from the array. After that, because of the rest parameter's presence, arr gets the rest of the values in the form of an array. The rest element only works correctly as the last variable in the list. As in, you cannot use the rest parameter to catch a subarray that leaves out the last element of the original array.

We can splice the array using destructing and rest too:

Example:

const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
  const [,,...arr] = list; // check the first 2 commas, they are left intentionally to remove the first 2 items from the array
  return arr;
}
const arr = removeFirstTwo(source);

On objects:

let person = {
    name: 'Max',     
    age: 27
}; 
let {name, age} = person; // Notice the {} instead of []

Object items are defined by their property name. So when destructuring an object, the exact name should be used for the variables. Example:

let person = {
    name: 'Shane',     
    age: 35
}; 
let {name, job} = person;

console.log(job); // this result into an error in the console

It is also possible to default some values to the variable of the destructured object. In any case the object does not have the property name, then the defaulted value will be used for the variable. Example:

let person = {
    name: 'Shane',     
    age: 35
}; 
let {name, job = 'Developer'} = person;

console.log(job); // => "Developer"

Object destructuring can also be made on function. Example:

let person = {
    name: 'Shane',     
    age: 35,
    greetme: function greetme() { console.log('Greetings'); }
}; 
let {name, greetme} = person;

greetme(); // => "Greetings"

Aliases can be defined to the property name in the destructured object variable if required. Then the variable will only be accessible using this alias name: Example:

let person = {
    name: 'Shane',     
    age: 35,
    greetme: function greetme() { console.log('Greetings'); }
}; 
let {name, greetme: Hello} = person;

console.log(greetme()); // => error in console
console.log(Hello()); // => "Greetings"

Use Destructuring Assignment to Pass an Object as a Function's Parameters

In some cases, you can destructure an object in a function argument itself. Consider the code below:

profileData: {
   name: 'Shane',
   age: 35,
   nationality: 'MU',
   location: 'Moka'
}

const profileRetrieve = (profileData) => {
  const { name, age, nationality, location } = profileData;
}

This effectively destructures the object sent into the function. This can also be done in-place:

const profileRetrieve = ({ name, age, nationality, location }) => { // notice the {} passed as an argument to destructure the object passed into the function
   const profileParagraph = `I, ${name}, of age ${age} lives at ${location}.`
}

profileRetrieve(profileData); // pass the object as an argument into the function

When profileData is passed to the above function, the values are destructured from the function parameter for use within the function.