Languages

JavaScript - can I set default value of property while destructuring object?

3 points
Asked by:
Inayah-Alexander
767

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
Answered by:
Inayah-Alexander
767

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
Answered by:
Inayah-Alexander
767

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join