Boolean() casting function
Boolean() casting function converts a value into its boolean equivalent. 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 |
The following code converts a nonempty string to Boolean type:
<!DOCTYPE html>
<html>
<head>
<title>Boolean Example</title>
<script type="text/javascript">
var aString = "Hello world!";
var aBoolean = Boolean(aString);
document.writeln(aBoolean); //true
</script>
</head>
<body>
</body>
</html>
The following code converts a zero value to Boolean type:
<!DOCTYPE html>
<html>
<head>
<title>Boolean Example</title>
<script type="text/javascript">
var anInt = 0;
var aBoolean = Boolean(anInt);
document.writeln(aBoolean); //false
</script>
</head>
<body>
</body>
</html>
Some statment, such as the if statement, automatically perform this Boolean conversion:
<!DOCTYPE html>
<html>
<head>
<title>Boolean Example</title>
<script type="text/javascript">
var aString = "Hello world!";
if (aString){
document.writeln("value is true");
}
aString = "";
if (aString){
document.writeln("value is true");
}else{
document.writeln("value is false");
}
aString = null;
if (aString){
document.writeln("value is true");
}else{
document.writeln("value is false");
}
</script>
</head>
<body>
</body>
</html>
Home
JavaScript Book
Language Basics
JavaScript Book
Language Basics
Data Types:
- JavaScript Data Types
- typeof Operator
- The Undefined Type
- null Type
- null vs undefined
- Boolean Type
- Boolean() casting function
- The Literials of Number Type
- Octal Integer
- Hexadecimal
- Floating-Point Values
- Value range
- NaN
- Number Conversions:Number(), parseInt() and parseFloat()
- Number() function
- parseInt()
- parseFloat()
- The String Type
- String Literals and Escapes
- Get the String Length
- Converting to a String with toString() method
- Convert Number to String with radix
- Convert to String with String() casting function