Boolean(...)
will convert any data type into either true
or false
.
Boolean("true") === true
Boolean("false") === true
Boolean(-1) === true
Boolean(1) === true
Boolean(0) === false
Boolean("") === false
Boolean("1") === true
Boolean("0") === true
Boolean({}) === true
Boolean([]) === true
Empty strings and the number 0 will be converted to false, and all others will be converted to true.
A shorter, but less clear, form:
!!"true" === true
!!"false" === true
!!-1 === true
!!1 === true
!!0 === false
!!"" === false
!!"1" === true
!!"0" === true
!!{} === true
!![] === true
This shorter form takes advantage of implicit type conversion using the logical NOT operator twice, as described in http://www.riptutorial.com/javascript/example/3047/double-negation----x-
Here is the complete list of boolean conversions from the ECMAScript specification
myArg
of type undefined
or null
then
Boolean(myArg) === false
myArg
of type boolean
then Boolean(myArg) === myArg
myArg
of type number
then Boolean(myArg) === false
if myArg
is +0
, ‑0
, or NaN
; otherwise true
myArg
of type string
then Boolean(myArg) === false
if myArg
is the empty String (its length is zero); otherwise true
myArg
of type symbol
or object
then Boolean(myArg) === true
Values that get converted to false
as booleans are called falsy (and all others are called truthy). See Comparison Operations.