Javascript Boolean


A Boolean object has two value : true and false. The syntax for creating a Boolean object is as follows:

// Constructor
new Boolean (value);
// conversion function
Boolean(value);

The value parameter can be a value to be converted to a Boolean object or a value stored by a Boolean object. The difference between these two syntaxes can be seen in the following example:

document.write(typeof(new Boolean(1)) + '<br />');
document.write(typeof(Boolean(1)));
Output
object
boolean

Obviously, the constructor (new keyword) gets an object that contains a boolean value, whereas using the conversion function results in a boolean value.

Summary: Boolean objects can be regarded as a special object, we can treat it as a Boolean value of a container.

Note

If the value parameter is set to 0, -0, null, "", false, undefined, or NaN, or omit the parameter, the Boolean object is set to false, otherwise true.

Note that although the Boolean object is set to false, it remains true in the if statement:

var obj1 = new Boolean(false);
if (obj1) {
   document.write('1');
} else {
   document.write('2');
}

This example wiil show output 1. The reason is that although obj1 is an object that is set to false, obj1 is a non-null object in the if statement, so it is meaningful to return true. This is independent of the Boolean value contained by the obj1 object.


Object property

Boolean prototype object supports property to increase or re-definition of the object properties and methods, see the detailed " prototype property of a JavaScript object ."


Object method

  • toString() : logical value to a string
  • valueOf() : Boolean to get the object's original value

JavaScript will implicitly call the toString() method when you want to print a Boolean object or have a similar string operation




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook