---
title: "Destructuring assignment"
url: "https://blog.beyondthecloud.dev/tips/destructuring-assignment"
category: "JavaScript"
tags: "lwc"
published: "2024-07-23"
---

# Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables.

### Destructuring assignment in LWC

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables.

The most popular use of destructuring assignment can be found in wire.

```javascript
@wire(getRecord, { recordId: "$recordId", fields: ["Account.Name"] })
wiredAccount({ error, data }) {
    if (data) {
        this.record = data;
    } else if (error) {
        console.error(error);
    }
}
```

Transformation from an object to an array.

```javascript
Object.entries(person).map(row => ({
    field: row[0],
    value: row[1]
}));
```

```javascript
Object.keys(person).map(key => ({
    field: key,
    value: person[key]
}));
```

```javascript
Object.entries(person).map(([property, value]) => ({
    field: property,
    value
}));
```

Destructuring in Function Parameters.

```javascript
import { LightningElement} from 'lwc';

export default class EventHandling extends LightningElement {
    handleEvent(event) {
        console.log(`Value of ${event.target.name} changed to ${event.target.value}`);
    }
}
```

```javascript
import { LightningElement } from 'lwc';

export default class EventHandling extends LightningElement {
    handleEvent({ target: { value, name } }) {
        console.log(`Value of ${name} changed to ${value}`);
    }
}
```

Destructuring with Default Values.

```javascript
import { LightningElement } from 'lwc';

export default class DefaultValueExample extends LightningElement {
    config = {
        theme: 'light'
    };

    getConfig() {
        const theme = this.config.theme;
        const layout = this.config.layout ?? 'standard';

        return `Theme: ${theme}, Layout: ${layout}`;
    }
}
```

```javascript
import { LightningElement } from 'lwc';

export default class DefaultValueExample extends LightningElement {
    config = {
        theme: 'light'
    };

    getConfig() {
        const { theme, layout = 'standard' } = this.config;
        return `Theme: ${theme}, Layout: ${layout}`;
    }
}
```
