1

While destructuring function argument, if the function argument is undefined how to handle it?

const product = {
    label: 'Notebook',
    price: 50
};

const destructSample = ({label, price}) => {
    console.log(label, price);
}

destructSample(product);
destructSample(undefined);

destructSample(undefined); throws following error

const destructSample = ({label, price}) => {
                         ^

TypeError: Cannot destructure property `label` of 'undefined' or 'null'.
    at destructSample (E:\PlayGround\NodeJs\nodeCourse\playground\destructuringError.js:6:24)
    at Object.<anonymous> (E:\PlayGround\NodeJs\nodeCourse\playground\destructuringError.js:11:1)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

How to resolve this? Thank you.

3
  • The proposed duplicate talks about partially defined objects, in the OP's case there's no object at all. Commented Sep 11, 2019 at 12:33
  • @georg The duplicate is about both. Commented Sep 11, 2019 at 12:33
  • 1
    @str: yes, the answer happens to be the same, but we're supposed to vote for duplicate questions, not similar answers. Commented Sep 11, 2019 at 12:36

1 Answer 1

10

A default value can be used

const product = {
    label: 'Notebook',
    price: 50
};

const destructSample = ({label, price}= {}) => {
    console.log(label, price);
}

destructSample(product);
destructSample(undefined);

Note:- default parameters will come into picture only when there is no arguments passed or undefined is passed as argument, so if you want to handle some more falsy value you can do something like this

const product = {
    label: 'Notebook',
    price: 50
};

const destructSample = (obj) => {
    let {label, price}= obj === undefined || obj === null ? {} : obj
    console.log(label, price);
}

destructSample(product);
destructSample(undefined);
destructSample();
destructSample(null);

Related question javaScript function - why my default argument fails?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.