Confusing JavaScript Syntax - Destructuring

Another useful new feature of ES2015 is the destructuring of object and arrays. Commonly, individual object properties or array elements need to be extracted, and reused over and over again. In earlier versions of JavaScript, creating variables and extracting the desired values is cumbersome and verbose. Destructuring streamlines the extraction process and reduces the code needed to accomplish the task.

Object Destructuring

Review the code below, the person object has two properties: firstName and lastName. These properties can be picked off of the object and stored in new variables named after the properties.

const person = {  
  firstName: 'Bob',
  lastName: 'Smith'
};

// picks off the firstName and lastName
// properties of the person object
// and stores the values in the firstName
// and lastName variables
const { firstName, lastName } = person;

// outputs firstName to the console
console.log(firstName);  
// outputs lastName to the console
console.log(lastName);

In addition to declaring variables with const (or let or var) the destructuring can be done within the parameter declaration of a function. Observe the code below.

const person = {  
  firstName: 'Bob',
  lastName: 'Smith'
};

// the firstName and lastName property will be picked
// from the object passed into the function
function getFullName({ firstName, lastName }) {  
  return firstName + ' ' + lastName;
}

console.log(getFullName(person));

If a different variable name is desired, then a colon followed by the desired variable name allows a property to be picked and assigned to different variable as shown here.

const person = {  
  firstName: 'Bob',
  lastName: 'Smith'
};

// picks off the firstName and lastName
// properties of the person object and
// stores the values in the fn and ln variables
const { firstName: fn, lastName: ln } = person;

// outputs fn to the console
console.log(fn);  
// outputs ln to the console
console.log(ln);

Also, default values can be specified when the specified property does not exist on the source object.

const person = {  
  firstName: 'Bob',
  lastName: 'Smith'
};

// picks off the firstName, lastName and
// age property
// age is not specified on person, so the
// default value is used
const { firstName: fn, lastName: ln, age = 18 } = person;

// outputs the default age to the console
console.log(age);

The advantage of destructuring is that it simplifies the code to reference property values, and it can improve the performance by capturing the value one time, instead of traversing the prototype chain each time a property is retrieved from the object.

const parent = {  
  propA: 'parent property value a'
};

const child = Object.create(parent);

child.propB = 'parent property value b';

const { propA, propB } = child;

// traverses the prototype chain to retrieve propA
console.log('propA: ' + child.propA);  
console.log('propB: ' + child.propB);

// no prototype chain to traverse to retrieve propA
console.log('propA: ' + propA);  
console.log('propB: ' + propB);

In the code above, each time a propA is referenced via the child object, the prototype chain must be traversed to retrieve the value of propA. Using destructuring, we can traverse the prototype chain once, and store the value in a new local variable. Depending upon how many times this value is needed, this could improve the performance of the application.

Array Destructuring

In addition to destructuring object, arrays can be destructured allowing items to be picked and stored in local variables. Instead of using curly braces for the destructure operation, square brackets are used instead. Observe the code below.

const colors = ['red','blue','white','yellow','orange'];

// items are destructured from the array
// using square brackets
const [ first, second ] = colors;

// outputs the color 'red'
console.log(first);

// outputs the color 'blue'
console.log(second);

Items can be skipped by specifying extra commas between variables as shown here.

const colors = ['red','blue','white','yellow','orange'];

// items are destructured from the array
// using square brackets
const [ first, , third ] = colors;

// outputs the color 'red'
console.log(first);

// outputs the color 'white'
console.log(third);

The second item is skipped, and only the first and third items are picked. To pick the remaining items from the array and store them in an array the rest operator can be used.

const colors = ['red','blue','white','yellow','orange'];

// items are destructured from the array
// using square brackets
const [ first, , third, ...otherColors ] = colors;

// outputs the colors ['yellow','orange']
console.log(otherColors);

Combining destructuring with the rest parameter is simpler way to shift (one or many) items off of the front of an array and producing a new array in an immutable manner. Additionally, default values can be specified in the variable declaration for the destructuring.

const colors = ['red','blue'];

// items are destructured from the array
// using square brackets
const [ first, second, third='white' ] = colors;

// outputs the color 'white'
console.log(third);

The Mozilla Developer Network (MDN) offers a great idea of using array destructure for swapping the values of two variables without using a third temporary variable. Check it out here.

let x = 1, y = 2;

// output original values
console.log(x,y);

// performs the swap
[x,y] = [y,x];

// outputs the swapped values
console.log(x,y);

By reversing the order of the array items on the right, the values are swapped with a single line of code.

Conclusion

Destructuring is a useful new feature in ES2015 for picking properties from objects or items from arrays. Destructuring can simplify code, as well as performance.