Destructuring assignment

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 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.

Don't do this
Object.entries(person).map(row => ({
    field: row[0],
    value: row[1]
}));
Don't do this
Object.keys(person).map(key => ({
    field: key,
    value: person[key]
}));
Do this
Object.entries(person).map(([property, value]) => ({
    field: property,
    value
}));

Destructuring in Function Parameters.

Don't do this
import { LightningElement} from 'lwc';

export default class EventHandling extends LightningElement {
    handleEvent(event) {
        console.log(`Value of ${event.target.name} changed to ${event.target.value}`);
    }
}
Do this
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.

Don't do this
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}`;
    }
}
Do this
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}`;
    }
}

Text and code were extracted from the original slide. Plain-text version of the whole catalog