Destructuring Assignment in JavaScript

Destructuring Assignment in JavaScript

ยท

5 min read

Destructuring assignment is a technique in JavaScript that is used to extract values from arrays and objects. This syntax allows us to write clean, concise, and readable code.

Destructuring assignment does not mutate arrays or objects in any way.

Array destructuring

Extracts values from the elements of an array.

Let's say we have an array of cars and we want to assign the values of some elements in the array to variables.

const cars = ['Toyota', 'BMW', 'Land Rover'];

Here is how we would do it in earlier versions of JavaScript:

const carOne = cars[0];
// 'Toyota'
const carTwo = cars[1];
// 'BMW'
const carThree = cars[2];
// 'Land Rover'

But with the introduction of destructuring assignment, we can shorten the snippet above into a single line of code.

const [carOne, carTwo, carThree] = cars;

console.log(carOne);
// 'Toyota'
console.log(carTwo);
// 'BMW'
console.log(carThree);
// 'Land Rover'

Cool right?๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿš€

Array destructuring with default parameters

Another benefit of using destructuring assignment is the ability to use default parameters which act as placeholders for undefined variables - variables with a type of undefined.

Here's a feel of how the code would look like using short-circuit evaluation.

const names = ['Ayobami'];
const firstName = names[0];
const lastName = names[1] || '(surname)';

NOTE: In this scenario, the default value of '(surname)' would be used if the value of names[1] is falsy.

Using default parameters:


const [firstName, lastName = '(surname)'] = ['Ayobami'];

console.log(`My name is ${firstName} ${lastName}.`);
// 'My name is Ayobami (surname).'

Skipping array elements

To skip elements in an array while destructuring, we simply append commas to the preceding element in the array until we reach the element we want to access.

const numbers = [1, 2, 3, 4, 5];

const [one, two, , , five] = numbers;

console.log(one);
// 1
console.log(two);
// 2
console.log(five);
// 5

Assigning values

Array destructuring can also be used to assign values to variables that have been created, or defined already. This is useful in situations where we have to assign values to multiple variables at once.

let a;
let b;

[a, b] = [1, 2];

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

Swapping values

Swapping the values of variables is as easy as switching the positions of the variables using array destructuring, as if the variables were elements of an array.

let a = 1;
let b = 2;

[a, b] = [b, a];

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

Object destructuring

Unpacks values stored as properties in an object.

Unlike array destructuring, object destructuring involves unpacking properties from an object using the key of that property. Let's say we have an object called user:

const user = {
    email: 'test@mail.com',
    password: 'random.ly',
    handle: 'discourse'
};

Accessing the properties of user using dot notation would look like this:

const email = user.email;
const password = user.password;
const handle = user.handle;

With object destructuring, we provide the properties we want to unpack from the object on the left side of the assignment operator =, and wrap them in a set of curly braces. The object to be destructured will be on the right side.

const { email, password, handle } = user;

console.log(email);
// 'test@mail.com'
console.log(password);
// 'random.ly'
console.log(handle);
// 'discourse'

Object destructuring with default parameters

Just as with array destructuring, we can also provide default values for the properties destructured from an object.

const { handle, verified = false } = user;

console.log(handle);
// 'test'
console.log(verified);
// false

Renaming a property from a destructured object

To change the name of a property destructured from an object, we append a colon to the property name from the destructured object followed by the new variable name.

const { handle: userHandle, verified: isVerified } = {
    handle: 'new',
    verified: false
};

console.log(userHandle);
// 'new'
console.log(isVerified);
// false

Even after renaming a property destructured from an object, we can still assign a default value to the new variable name.

const { gender, handle: userHandle = 'default', verified: isVerified = false } = {
    gender: 'male'
};

console.log(gender);
// 'male'
console.log(userHandle);
// 'default'
console.log(isVerified);
// false

Accessing nested object properties

To access the properties of a nested object, we destructure the outer object as we would normally. As for the inner object, we wrap its properties in another set of parentheses.

const user = {
    names: {
        firstName: 'John',
        lastName: 'Doe'
    },
    handle: 'johndoe'
};

const { names: { firstName, lastName } } = user;

console.log(`${firstName} ${lastName}`);
// 'John Doe'

This syntax still allows us to use default parameters and rename properties from the destructured object, just as we did before.

Object destructuring in function parameters

When expecting an object as a function parameter, we can destructure the object on the fly to extract the properties we need from that object.

const userDetails = {
    email: 'random@mail.com',
    password: '12345678'
};

const printUserDetails = ({ email, password }, isVerified) => {
    console.log(email, password, isVerified);
};

printUserDetails(userDetails, false);

Destructuring objects in an array

Unpacking properties from objects in an array is the same process as for a normal object. All we have to do is loop through the array, and then destructure the object on each iteration.

const sportList = [
    {
        name: 'football',
        rating: 8
    }, 
    {
        name: 'hockey',
        rating: 7
    }, 
    {
        name: 'basketball',
        rating: 10
    }, 
    {
        name: 'rugby',
        rating: 9
    }
];

sportList.forEach(({ name, rating }) => {
    console.log(`Name: ${name}`);
    console.log(`Rating: ${rating}`);
});

When iterating over an array of objects using array iterator methods like map, filter and the likes, we can still destructure the object on each iteration.

When using arrow functions, and we want to destructure properties from an object, it is necessary to wrap the function parameters within a set of parentheses. This has to be done even if we have a single parameter of a destructured object, if not an error will be thrown by the compiler.

Tip ๐Ÿ’ก: Destructuring assignment can also be used to work with rest parameters and spread syntax.


Thanks for reading.๐Ÿ˜

Feel free to react and leave a comment.๐Ÿ’ฏ

ย