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

269
Visualizações
Why does destructuring on boolean is working in javascript?

why destructuring a boolean is working. For example

const condition = true
const toto = { name: 'toto' }

const other = {
   other: 'other',
   ...condition && toto
}
console.log({ other }) // { other: 'other', name: 'toto' }

const falseCondition = false

const otherWithoutToto = {
   other: 'other',
   ...falseCondition && toto
}

console.log({ otherWithoutToto }) // { other: 'other' }

In the case of false boolean, we don't add property, otherwise we will. Actually it's working well but someone can explain me why is it possible?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

What you're using here isn't destructuring, it's object property spread. It requires that the expression to the right-hand side (RHS) of the ... evaluates to either an object or something that can be converted to one (with exceptions for null and undefined). It then takes the own-enumerable properties from the object and copies them to the object being created. In the case of your example, two possibilities can occur for the below code:

...(condition && toto)
  1. condition is true, and so the above expression evaluates to the object toto. It doesn't evaluate to a boolean, but rather the last truthy value, which in your case is the object toto. The object property spread syntax then takes the own-enumerable properties from the object and adds them to the object being created.

  2. condition is false, and so the above expression evaluates to the value false. This means that JavaScript treats the above code as ...false. As false is a primitive and not an object, JavaScript tries to convert it to one by wrapping it in a boolean object:

    ...new Boolean(false)
    

    now that the RHS of the ... has been converted to an object, JavaScript then takes the own-enumerable properties of the boolean object and adds them to the object being created. As the boolean doesn't have any own properties which are enumerable, nothing is added to the created object.

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