support@90-10.dev

JavaScript Destructuring

Destructuring is the process of unpacking (extracting) data from arrays or objects, into distinct variables to make it easier to work with complex data structures.

Array Destructuring

Given an array, we can "extract" some of its content and assign them to variables in a single statement, using square brackets []:

let colours = ['red', 'blue', 'green']
let [colour1, colour2] = colours
console.log(colour1)  // prints: red
console.log(colour2)  // prints: blue

It is possible to ignore certain values when required - notice the extra comma between colour1 and colour2 in the example below:

let colours = ['red', 'blue', 'green'];
let [colour1, , colour2] = colours;
console.log(colour2)  // prints: green

Undefined

If not enough values are present, the destination will be undefined (as expected when declaring but not assigning variables):

let colours = ['red', 'blue']
let [colour1, colour2, colour3] = colours
console.log(colour43)  // prints: undefined

Default value

However, default values can be provides:

let colours = ['red', 'blue']
let [colour1, colour2, colour3 = 'yellow'] = colours
console.log(colour3)  // prints: yellow

Object Destructuring

This will feel very similar to the destructuring from arrays - however, the names of the variables to destructure to must match the name of the object properties:

let colour = { name: 'blue', score: 42}
let {name, score} = colour
console.log(name)   // prints: blue
console.log(score)  // prints: 42

Renaming

To unpack to different variable names, we need to specify both them alongside the object properties:

let colour = { name: 'blue', score: 42};
let {name: colourName, score: colourScore} = colour;

Default values

Just like before, we can specify default values:

let colour = { name: 'blue', score: 42};
let {
    id: colourId = 1, 
    name: colourName, 
    score: colourScore
} = colour;
console.log(colourId)  // prints: 1
console.log(colourName)  // prints: blue

Tip: Multiple assignment via destructuring

Sometime we need to assign values to multiple variable at the same time and destructuring makes is simpler and visually more appealing:

let colour, score;
[colour, score] = ['blue', 42];

Tip: Swap values

Another common scenario is when swapping the values of 2 variables - usually it requires a third temporary variable to hold one the values. With destructuring assignment, it becomes much easier:

let x = 1
let y = 2
[x, y] = [y, x]
console.log(x)  // prints: 2
console.log(y)  // prints: 1

Take Away

JavaScript destructuring is a powerful feature that can make our code more concise and readable, by allowing us to extract values from arrays and objects with ease and provides us with more control over variable assignment.