kevin parra
kevin parra

Reputation: 446

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()?

Upvotes: 2

Views: 542

Answers (1)

Yago Biermann
Yago Biermann

Reputation: 1813

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.

Upvotes: 1

Related Questions