Destructing in JavaScript

In JavaScript/TypeScript, if you’re using the Prefer destructuring from arrays and objects (prefer-destructuring) eslint rule, you’ll want to use destructing syntax to get values from objects and arrays.

If we imagine we have an object like this

class Person
{
   firstName: string;
   lastName: string;
}

The to get the firstName from a Person instance, we tend to use

const firstName = person.firstName;

Instead this rule prefers that we use the following syntax

const { firstName } = person;

If for some reason (for example in React if you’re destructing state which may have been changed) you have need to get the value using destructing syntax but assigned to a new variable/value name, then we use

const { firstName: fname } = person;