EN
JavaScript - can I set default value of property while destructuring object?
2
answers
3
points
Is there a possibility to set default value of object property while destructuring it?
At some point of my code the property can be undefined and I want it to have a default value.
I need something like:
// ONLINE-RUNNER:browser;
const object = { a: 1, b: 2 };
let { c } = object; // c is undefined here
if (c === undefined) {
c = 3; // if c is undefined sets the default value
}
console.log(c); // 3
2 answers
4
points
Yes, you can.
As example, React component with default values in props:
const MyComponent = ({ name = 'John', age = 21 }) => {
return (
<div>
<div>Name: {name}</div>
<div>Age: {age}</div>
</div>
);
};
// Usage example:
<MyComponent />
<MyComponent name="Kate" />
<MyComponent age={25} />
<MyComponent name="Kate" age={25} />
0 comments
Add comment
3
points
Yes, you can set the default value while destructuring the object.
Quick solution:
// ONLINE-RUNNER:browser;
const object = { a: 1, b: 2 };
const { c = 3 } = object; // if c is undefined sets its default value
console.log(c); // 3
0 comments
Add comment