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?