Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructuring optional properties

I would like to create a function that takes one optional property called verbose, and if it’s not specified it defaults to true. Here is an example:

function Counter(n=0, {verbose=false}) {
    return function() {
        n++;
        if (verbose) console.log(n);
        return n;
    }
}
let c1 = Counter(0, {verbose: true});
c1(), c1(), c1();

Everything works fine. However, as soon as I call it without the object param, I get an error:

function Counter(n=0, {verbose=false}) {
    return function() {
        n++;
        if (verbose) console.log(n);
        return n;
    }
}
let c1 = Counter(0);
// TypeError: Cannot read property 'verbose' of undefined

Why does this occur, as I thought the whole point of having an object that can be destructured in the argument list is the suggested way to have a bunch of optional arguments that can be called. What am I doing wrong here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t put the default in the destructuring pattern, put it in a default value that’s assigned to the whole object.

function Counter(n=0, {verbose} = {verbose: false}) {
    console.log(verbose);
    return function() {
        n++;
        if (verbose) console.log(n);
        return n;
    }
}
let c1 = Counter(0);
let c2 = Counter(0, {verbose: true});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading