Categories
ES6 JavaScript

Intro to Destructuring JavaScript Objects and Arrays

What is Destructuring?

Destructuring or Destructuring assignment is a syntax we can use to extract properties from objects or values from arrays in JavaScript assigning then to a variable. Let’s use the next object as a starting point.

const car = {
  maker: 'Toyota',
  model: 'Corolla',
  color: 'Yellow',
  engine: {
    Displacement: 2.0,
    cylinders: 4
  },
  license_plate: 'ASSF4287',
};

Destructuring Objects

Sometimes we need access to the properties values of an object through a variable, something like:

const license_plate = car.license_plate;
const maker = car.maker;
const color = car.color;

Using this syntax creates repetitive code and you’ll find yourself typing the same code again and again. This last snipe can be reduced to one line using the new destructuring syntax from ES6 as follow.

const { license_plate, maker, color } = car;

console.log(license_plate); //'ASSF4287'
console.log(maker); //'Toyota'
console.log(color); //'Yellow'

This line of code simplifies the way that we can create high-level variables to access those properties that we need in a faster and cleaner way. We can also access nested object properties or use default values in case the property we try to access doesn’t exist.

const {
  license_plate = 'unknown', //Using a default value.
  maker,
  color,
  engine: { displacement }, //Accesing nested properties.
} = car;

console.log( engine.displacement ); //2

Destructuring Arrays

Like Objects, arrays can be destructuring using the new ES6 syntax. Let’s use the next array as the starting point for our examples.

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

We assign values from a specific index in the array to a variable follow the old syntax, like:

const red = colors[0];
const yellow = colors[1];
const metalizedBlue = colors[4][0];

As our example for objects, this method makes us write the same thing again and again. If we use the destructuring method we can reduce all this code to one line, improving the readability and simplified our code.

const [red, yellow, , , [metalizedBlue]] = colors;

console.log(red); //'red'
console.log(yellow); //'yellow'
console.log(metalizedBlue); //'metalized blue'

In this example, we can see how easy it is to create high-level variables from the values of our array, we just have to place the name of the variable in the place of the array where is the value that we want to assign to this variable. Also, we can skip any index by leave an empty spot, besides we can access nested arrays using the same syntax rules. We can use this same syntax to create variables from an array nested in an object mixing both techniques.

Spread Syntax

Using . . . before any iterable, we can assign the rest of the items in an array to a specific variable. Let’s create a quick example.

const [red, yellow, ...otherColors] = colors;

console.log(red); //'red'
console.log(yellow); //'yellow'
console.log(otherColors);
/**['blue',
 *   'white',
 *   ['metalized blue', 'metalized red', 'metalized orange'],
 *  ];
 **/

Destructuring Function Parameters

Destructuring can be very useful to create local variables from the parameters of a function. We can require an object as parameters for our function, this way whoever uses our function in the future doesn’t need to remember the specific order of the parameters and instead.

const car = {
  maker: 'Toyota',
  model: 'Corolla',
  color: 'Yellow',
  engine: {
    Displacement: 2.0,
    cylinders: 4,
  },
  license_plate: 'ASSF4287',
};

const display = ({
  maker,
  model,
  color = 'unknown',
  engine: { size, cilinders },
  license_plate = 'unknown',
  ...otherProperties
}) => {
  console.log('Maker & Model: ' + maker + ' ' + model);
  console.log('Color: ' + color);
  console.log('Engine: ' + size + 'L ' + cyliners + 'CL');
  console.log('License Plate: ' + license_plate);
};

display(car);

display(car);
 /**
 * 'Maker & Model: Toyota Corolla'
 * 'Color Yellow'
 * 'Engine: 2L 4CL'
 * 'License Plate: ASSF4287'
 **/

Conclusion

The use of destructuring syntax helps us write clear and simple code even when using complicated data structures. This is some information and examples about what you can do with destructuring in JavaScript ES6 but if you want to increase your knowledge about this subject visit MDN for more information.

Happy Coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.