Categories
JavaScript

How to Convert JavaScript Variable to Boolean

Spread the love

It is easy to convert anything a boolean in JavaScript. Truthy values will be converted to true and falsy values will be converted to false. There are 2 ways to convert variables to a boolean. There is the Boolean function, and there is the !! shortcut.

There are 6 kinds of falsy values:

  • false
  • 0
  • empty string: "" , '' , or ``
  • null
  • undefined
  • NaN — not a number value

Anything else is truthy.

If you evaluate them as boolean like so, you get:

Boolean(false); // false
Boolean(0); // false
Boolean(""); // false
Boolean(''); // false
Boolean(``); // false
Boolean(undefined); // false
Boolean(null); // false
Boolean(NaN); // false

as opposed to truthy values like objects, which are anything else but the values above:

Boolean({}) // true
Boolean(true) // true
Boolean([]) // true

You can also use the !! shortcut to cast to Boolean, the right ! cast the variable into a boolean and negate the value, and the left ! negate it back to the actual boolean value.

!!(false); // false
!!(0); // false
!!(""); // false
!!(''); // false
!!(``); // false
!!(undefined); // false
!!(null); // false
!!(NaN); // false

Similarly for truthy values:

!!({}) // true
!!(true) // true
!!([]) // true

With shortcut evaluation, boolean ANDs and ORs are evaluated up to the first truthy value:

const abc = false && "abc"; // false, since false is false and "abc" is trueconst def = false || "def"; // true, since false is false and "def" is true

Leave a Reply

Your email address will not be published. Required fields are marked *