DEV Community

Discussion on: JavaScript object destructuring usages you must know

Collapse
froxxninethree profile image
Froxx93

I would advise against variable definitions during destructing like this:

const {name, dept, message = `${name} is ${dept}`} = employee;
Enter fullscreen mode Exit fullscreen mode

What you're actually doing here is simply defining a default value for employee's property message. So as a side effect if your object actually has a property with that name, it will simply override your default value.

const employee = {
  name: 'John',
  dept: 'Service',
  message: 'This is me!'
}
const {name, dept, message = `${name} is ${dept}`} = employee;
console.log(message); // logs 'This is me!'
Enter fullscreen mode Exit fullscreen mode

It works, and you could still use it, but be aware of what's actually happening and consider writing 1 line of extra code to prevent possible unexpected behaviour.

Apart from that – A good overview to destructing. Gj!