Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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});

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!