Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda