How to Convert Any Value to a Boolean in JavaScript?

In JavaScript, you can explicitly convert any value or expression to boolean in the following two ways:

  1. Using the Double NOT Operator (!!);
  2. Using the Boolean Object Wrapper.

Using the Double NOT Operator (!!)

You can simply use the logical NOT operator (!) twice to cast any value to its boolean equivalent.

In the following examples you can see how falsy values are converted to boolean false:

!!0
!!''
!!NaN
!!null
!!undefined
!![].length
// ...

Similarly, when you use double negation on a truthy value, it will result in boolean true:

!!1
!!'foo'
!!'false'
!![]
!!{}
!![1, 2, 3].length
// ...

Please be aware that all non-falsy values, including any object, an empty array ([]), or the string "false", are cast to boolean true.

You need double negation because when you use the logical NOT operator (!) only once, it negates the operand. This means that it would convert all falsy values to boolean true and all truthy values to boolean false:

!false // true
!true // false

Therefore, if you negate the result again you would be casting the value itself to its correct boolean equivalent.

Using the Boolean Object Wrapper

You can use the Boolean object wrapper to convert any value to its boolean equivalent.

In the following examples you can see how falsy values are converted to boolean false:

Boolean(0)
Boolean('')
Boolean(NaN)
Boolean(null)
Boolean(undefined)
Boolean([].length)
// ...

Similarly, in the following examples you can see how it converts truthy values to boolean true:

Boolean(1)
Boolean('foo')
Boolean('false')
Boolean([])
Boolean({})
Boolean([1, 2, 3].length)
// ...

Please be aware that all non-falsy values, including any object, an empty array ([]), or the string "false", are converted to boolean true.

Please do not confuse the Boolean object wrapper with the Boolean constructor. The former returns a primitive, while the latter is used to create a new instance of the object.

The confusion with using the Boolean constructor (in terms of converting a value into boolean) lies in the fact that the object itself is always truthy (even if the value you passed to the constructor at the time of object instantiation was a falsy value). To illustrate this, consider the following:

const bool = new Boolean(false);

if (bool) {
    // code is executed
}

console.log(!!bool); // true

For this reason, to convert non-boolean values to boolean, you should not use the Boolean constructor and use the Boolean object wrapper instead.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.