Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!