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

177
Visualizações
Should I use Boolean(value) or can I compare directly?

I usally write this kind of conditions:

if (title && content){
// code
}

But then I see this example:

const canSave = Boolean(title) && Boolean(content) && Boolean(userId)

And they used canSave to pass in to disabled prop in a button.

Is it a best practice to use Boollean instead of just doing the following?

const canSave = title && content && userId

In what cases should I use Boolean()?

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

0

The main goal of Boolean function is to convert a value to boolean, in your case makes sense to convert to boolean before assign to a variable because if you try to do it that way:

const canSave = title && content && userId

the variable canSave will assign the value of userId and will ignore the rest, but if you convert the values to boolean, the variable canSave will assign the result of a comparison between these values. Another reason to use the boolean function could be to convert a value before pass it to a function who only accepts boolean as parameters, like so:

const foo = (bar) => {
  if(typeof bar !== "boolean") {
    throw new Error("not a boolean")
  }
  // do something else
}

foo(2) // Error
foo(Boolean(2)) // Ok

In this case makes sense to convert the value to boolean, maybe another case would be convert the value before saving to a database. As values like positive numbers, strings, arrays and objects are always true and zero or negative numbers, empty strings, undefined and null are false, there's some cases that doesn't make sense to convert it, like in a conditional statement, like so:

if (title && content && userId) {
  // do something
}

These variables will be casts to a boolean already, so converting it will just create redundancy in your code.

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