Destructuring in JavaScript

Destructuring in JavaScript

Introduction

destruction array

The term “destruction” means “extracting” data from a data structure (object or array) and creating new smaller structures that are assigned values based on the “extracted” data.
Before ES2015, it was necessary to write code that would perform destructuring, but luckily with the new JavaScript standard came a syntax that allows the JavaScript compiler to automatically perform this work for us. This syntax is called “destructuring assignment”, and it does exactly what the name says, it assigns values from a structure to new variables.

Example
“Manual” destructuring

New ES6 syntax

NOTE: [a,b,c] from the previous example new syntax NOT AN ARRAY ! ! !
When square brackets (or curly braces) are to the left of the equals sign, it indicates a variable assignment pattern. They allow us to define to the JavaScript compiler how and under which variable name to store destructured values.

Array Destructuring

Template for accepting “excess” data

If we don’t know the number of destructed values, and they are important to us, e.g. only the first two we will use rest parameter:

Make sure that the rest parameter must be the last in the template, otherwise the compiler will throw an error!

Value missing from template

If there are fewer destructible elements compared to the template, then the excess variables from the template are assigned the value “undefined”.

Total lack of value

A specific case is when the structure being destroyed has no value, ie. when we destroy a structure that has no value. The compiler reports an error because the structure is not iterable. This case occurs if the function from which the iterator is expected returns “null” for some reason:

Avoiding program crashes and unpleasant situations is solved as follows:

Default values

If we want to ensure that the variable from the template has a value even if it does not have a destructed value, then we define a default value in the template:

Variable replacement

Destructing can also be useful if we want to replace the values of two variables:

Ignoring destructed values

By simply not defining a variable name within the template, we can ignore the destructed value:

Destructing nested arrays

Destructing an object

Assigning new variable names

Defining default values

Template for accepting excess variables

Destructing nested objects:

Destructing an object by for-of iteration