Convert to boolean
suggest changeBoolean(...) 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
Falsy values become false: false, 0, -0, 0n, "", null, undefined, and NaN. Everything else becomes true, including the strings "false" and "0", and ordinary objects. In browsers, the legacy document.all object is the exception that is falsy.
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 Double negation.
ToBoolean in the ECMAScript specification works as follows:
- if
myArgisundefinedornull, thenBoolean(myArg) === false - if
myArgis a boolean, thenBoolean(myArg) === myArg - if
myArgis a number, thenBoolean(myArg) === falseifmyArgis+0,-0, orNaN; otherwisetrue - if
myArgis a string, thenBoolean(myArg) === falseifmyArgis the empty string (its length is zero); otherwisetrue - if
myArgis a BigInt, thenBoolean(myArg) === falseifmyArgis0n; otherwisetrue - if
myArgis a symbol or an ordinary object, thenBoolean(myArg) === true
Values that convert to false are called falsy (and all others are called truthy). See Comparison operations.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents