To convert a truthy or falsy value to a boolean, pass the value to the boolean object - Boolean(myValue) . The boolean object converts the passed in value to true if it's truthy, otherwise it converts it to false .
To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .
in a boolean context (if statement, &&, ||, etc.). So someone designing a language has to decide what values count as "true" and what count as "false." A non-boolean value that counts as true is called "truthy," and a non-boolean value that counts as false is called "falsey."
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
You can use Boolean(obj)
or !!obj
for converting truthy/falsy
to true/false
.
var obj = {a: 1}
var to_bool_way1 = Boolean(obj) // true
var to_bool_way2 = !!obj // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With