JavaScript Boolean Object

Boolean data type is used to represent true/false in codes. Boolean object is an object wrapper for using true or false values in a script in an HTML page. JavaScript Boolean object is used to create an object variable that can be used and manipulated using the properties and methods.

Creating a JavaScript Boolean Object

A Boolean object can be created by using the Boolean constructor. The syntax for creating Boolean object is

var object-var =new Boolean(value-for-object);

var and new- keywords

object-var- is the user given name to the Boolean object

Boolean = Constructor of Object Class

Value- the object is initialized with this value. If you omit the value-for-object or it is not a valid value then the Boolean Object gets a false value. The invalid values are 0, empty string, null, undefined or NaN.

Example

var ready_to_go=new Boolean(false);

JavaScript Boolean Properties

Boolean object has only one property and it is length. It represents the length of the value held in a Boolean object. Since value is always 0 or 1 it will always return integer value 1 (for both true/false or 0/1 values stored). It can be accessed by using the length property with a JavaScript object combined with dot operator.

object-var.length

JavaScript Boolean Methods

Two methods can be used with JavaScript Boolean objects. They either return some value or do some conversion/ evaluation.

toString ()

This Boolean method returns the string representation of the Boolean object value. The string output of this method can be stored in a variable or can be printed using the document.write() method or an alert box.

valueOf ()

valueOf Boolean method returns the primitive representation of the Boolean object value passed to this method value. The output of this method can be printed using the document.write() method or in an alert box.

Example using Boolean Object

<TITLE> Welcome to CSVeda.com </TITLE>
<SCRIPT LANGUAGE="javascript">
num1= 30;
str1= "Welcome to CSVeda.com";
var booObj1=new Boolean(str1);
var booObj2=new Boolean(num1);
document.write("<br> length property = "+Boolean.length);
document.write("<br> Variable 1 "+booObj1.toString());
document.write("<br> Variable 2 "+booObj2.valueOf());
</SCRIPT>