Javascript Boolean Object

Javascript boolean object can have logical values either true or false. JavaScript implicitly uses the Boolean object whenever a Boolean data type is converted to a Boolean object.

Variable type Boolean does not support any quotes for example - "true" is not equal to true, "true" will be considered as a string.

Syntax

<html>
<html>
<head>
<title>Javascript Boolean Object</title>
<SCRIPT LANGUAGE="JavaScript">
var val = new Boolean(value);
</SCRIPT>
</head>
<body>
</body>
</html>

JavaScript pitfalls: null, false, undefined and NaN

Comparison operators

Zero - 0 : Evaluates to false in boolean operations. Always use === when comparing to the number 0.

Javascript Boolean Example

<html>
<head>
<title>Javascript Boolean Object</title>
<SCRIPT LANGUAGE="JavaScript">
var x = 0;
var y = false;

alert(x == y)   // return true
alert(x === y)  // return false
</SCRIPT>
</head>
<body>
</body>
</html>

Empty - "" : Evaluates to false in boolean operations. Always use === when comparing to an empty string.

Javascript Boolean Example

<html>
<head>
<title>Javascript Boolean Object</title>
<SCRIPT LANGUAGE="JavaScript">
var x = null;
var y = false;

alert(x == y)     //return true
alert(x === y)    //return false
</SCRIPT>
</head>
<body>
</body>
</html>

Undefined : If a variable has not declared or assigned yet then that variable will be given a special undefined value.

Javascript Boolean Example

<html>
<head>
<title>Javascript Boolean Object</title>
<SCRIPT LANGUAGE="JavaScript">
var x;
var y = false;

typeof(x)     //return undefined

alert(x == y)  //return true
alert(x === y) //return false
</SCRIPT>
</head>
<body>
</body>
</html>

NaN : Not a Number, generated when arithmetic operations return invalid results.

Javascript Boolean Example

<html>
<head>
<title>Javascript Boolean Object</title>
<SCRIPT LANGUAGE="JavaScript">
var x = 10/zero;
alert(x);               //return NaN

var x = 10/zero;
alert(x == x)           //return false
</SCRIPT>
</head>
<body>
</body>
</html>

Boolean Properties

PropertyDescription
constructor This will returns a reference to the Boolean function that created the object.
prototype This prototype property allows you to add properties and methods to an object.

Boolean Functions

Here is a list of each function of boolean object with description.

FunctionsDescription
toSource() This will returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
toString() This will returns a string of either "true" or "false" depending upon the value of the object.
valueOf() This will returns the primitive value of the Boolean object.