Use boolean casting function in Javascript
Description
All types of values have Boolean equivalents in Javascript.
To convert a value into its Boolean equivalent, use Boolean() casting function.
The following table lists the outcomes of Boolean()
casting function:
Data Type | True | False |
---|---|---|
Boolean | true | false |
String | nonempty string | empty string("") |
Number | nonzero number and infinity | 0, NaN(NotANumber) |
Object | Any object | null |
undefined | N/A | Undefined |
Example
The following code converts values to Boolean type:
var aString = "Hello world!";
var aBoolean = Boolean(aString);
console.log(aBoolean); //from w w w . j av a 2 s . c o m
var anInt = 0;
var aBoolean = Boolean(anInt);
console.log(aBoolean);
The code above generates the following result.
Note
These conversions are important because flow-control statements, such as the if
statement, automatically perform this Boolean conversion, as shown here:
var message = "hi!";
if (message){
console.log("Value is true");
}
In this example, the console.log is called because the string message is automatically converted
into its Boolean equivalent, which is true
.
The code above generates the following result.