Convert truthy or falsy to an explicit boolean, i.e. to True or False
Yes, you can always use this:
var tata = Boolean(toto);
And here are some tests:
for (var value of [0, 1, -1, "0", "1", "cat", true, false, undefined, null]) {
console.log(`Boolean(${typeof value} ${value}) is ${Boolean(value)}`);
}
Results:
Boolean(number 0) is false
Boolean(number 1) is true
Boolean(number -1) is true
Boolean(string 0) is true
Boolean(string 1) is true
Boolean(string cat) is true
Boolean(boolean true) is true
Boolean(boolean false) is false
Boolean(undefined undefined) is false
Boolean(object null) is false
!!o
is also shorthand of Boolean(o)
and works exactly same.
(for converting truthy/falsy
to true/false
).
let o = {a: 1}
Boolean(o) // true
!!o // true
// !!o is shorthand of Boolean(o) for converting `truthy/falsy` to `true/false`
Note that