Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda