Object Destructuring

Assign with Destructuring

In JavaScript, we can use Destructuring to assign properties of an object to a variable. In this post, we’ll see how to use destructuring and its advantages.

JavaScript Object Destructuring

Let say we have an object called user, and we need some values

const user = {
    userName: 'Dexter Morgan',
    userRole: 'Analyst',
    userContact:{
    email: '[email protected]',
    phone: 99999999
    }
}
const userName = user.userName;
const userRole= user.userRole;
const phone = user.userContact.phone;

This is fine but we have some redundancy here especially if our variable name is the same as that of the property and if look at some nested objects there can be higher chances of errors. Below is the same code, using destructuring.

const user = {
  userName: "Dexter Morgan",
  userRole: "Analyst",
  userContact: {
    email: "[email protected]",
    phone: 99999999,
  },
};

const { userName, userRole } = user;

// For nested properties
const {userContact: { phone }} = user;

Yes, much better but what if the variable names are different from the keys?

const user = {
  userName: "Dexter Morgan",
  userRole: "Analyst",
  userContact: {
    email: "[email protected]",
    phone: 99999999,
  },
};

const { userName: fullName, userRole: role } = user;

// For nested properties
const {
  userContact: { phone: mobile },
} = user;

Alias

The syntax for destructuring with a new variable name

const { propertyName: variableName } = object;

Default values

We can also set some default values

const { userName = "default value" } = user;

Dynamic property names

const user = {
  userName: "Dexter Morgan",
  userRole: "Analyst",
};

const nameProp = "userName";
const { [nameProp]:name, userRole } = user;

console.log(name);
> Dexter Morgan

Existing variables

Destructure and already existing variable

const user = {
  number: 21,
};

({ number } = user);

// we use () to let js know this is an expression
// else it will result in an error

console.log(number);
>  21

Handling null/undefined/empty objects

Whatever may be the case we get undefined, in case you want a fallback we can set default values or use the Nullish Coalescing Operator. And yes, we can restructure function return values.

let getUser = () => {};
let getUser = () => null;
let getUser = () => undefined;

const { userName, userRole } = getUser;
console.log(userName, userRole);

> undefined undefined

Array destructuring

It goes like this and we can skip elements using commas.

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

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

console.log(one, two, three, five);
> 1 2 3 5

Conclusion

once I knew about object-destructuring, I’ve started using it everywhere. Using this concept we can write clean code, less code, and use const everywhere.
Do you like Destructuring?