JavaScript Destructuring: Arrays, Functions, and Objects

Destructuring is a powerful feature in JavaScript that allows you to extract values from arrays, objects, and function parameters easily.

Array Destructuring

Using array destructuring we can extract values from an array and assign them to variables in a concise way.

Example

const myArray = [1, 2, 3];

const [first, second, third] = myArray;

console.log(first);
console.log(second);
console.log(third);

Output

Array Destructuring

Also, note that you can also skip elements by omitting them as per the following example.

const myArray = [1, 2, 3];
const [first, second, third] = myArray;

console.log(first);
console.log(second);
console.log(third);

Output

Array Destructuring Omitting

We can also use the rest syntax to collect the remaining elements as per the below example.

const myArray = [1, 2, 3];

const [first, ...rest] = myArray;

console.log(rest);

Output

Collect

Object Destructuring

Using Object destructuring we can extract values from an object and assign them to variables in a concise way.

Example

const myObject = { a: 1, b: 2, c: 3 };

const { a, b, c } = myObject;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

Output

Extract value

In the same way, we can elaborate on the Object destructuring as per the below example.

const myObject = { a: 1, b: 2, c: 3 };

const { a: x, b: y, c: z } = myObject;

console.log(x);
console.log(y);
console.log(z);

Output

Object

Also, we can able to use object destructing for assigning default values as per the following example.

const myObject = { a: 1, b: 2, c: 3 };

const { a = 0, b = 0, d = 0 } = myObject;

console.log(d);

Output

Assigning

Function Parameter Destructuring

Function parameter destructuring is also possible in JavaScript to assign values for the parameters used in the function.

Example

function myFunction({ a, b }) {
    console.log(a, b);
}

const myParams = { a: 1, b: 2 };

myFunction(myParams);

Output

Assign value

Function destructuring can also be used for assigning default values for the parameters in functions.

Example

function myFunction({ a = 0, b = 0 }) {
    console.log(a, b);
}

myFunction({ a: 1, b: 2 });

Output

Default value

Similarly, we can also use a combination of array and object destructuring as follows

function myFunction([x, y], { z }) {
    console.log(x, y, z);
}

myFunction([1, 2], { z: 3 });

Output

Array and Object

Moreover, destructuring methodology is widely used in modern JavaScript, making code more readable and concise. It's especially helpful when dealing with complex data structures or passing around multiple parameters.