JS Tip of the Day: Reduce Code with Destructuring

Reduce Code with Destructuring
Version: ES2015
Level: Intermediate

Destructuring is a process that allows you to copy properties from an object into other individual variables. Destructuring comes in two forms: array and object.

Array destructuring works on any iterable and uses ordering to copy values from the iterable into variables within the current scope.

let myArray = [1, 2, 3];
let [one, two, three] = myArray;
console.log(one, two, three) // 1, 2, 3

The destructuring expression here would be the same as saying:

let one = myArray[0];
let two = myArray[1];
let three = myArray[2];

Object destructuring, on the other hand, works with any object, but instead of using order, it uses the property names in the object to create new variables.

let myObject = { a: 1, b: 2, c: 3 };
let { a, c } = myObject;
console.log(a, c); // 1, 3

The destructuring expression here would be the same as saying:

let a = myObject.a;
let c = myObject.c;

Using destructuring this way can reduce the amount of code you write, not just by reducing your object references into single variables, but also by allowing you to do so in a single line of code.

What was covered here so far only scratches the surface of destructuring. There’s a lot more to learn about this feature which will be touched upon later on.

More info:

1 Like