Boolean in JavaScript:

Boolean is a primitive data type in JavaScript. Boolean can have only two values, true or false. It is useful in controlling program flow using conditional statements like if..else, switch, while, do..while.

Example: Boolean

var YES = true;

var NO = false;

The following example demonstrates how a Boolean value controls the program flow using if condition.

Example: Boolean

var YES = true;
var NO = false;

    alert("This code block will be executed");

    alert("This code block will not be executed");

Any type of comparison will return a Boolean result.

Example: Boolean

alert(1 > 2); // false

alert(10< 9); // false

alert(5 == 5); // true

Boolean object:

JavaScript includes Boolean object to represent true or false. It can be initialized using new keyword.

Example: Boolean object

var bool = new Boolean(true);

alert(bool); // true

JavaScript treats empty string (""), 0, undefined and null as false. Everything else is true.

Example: Boolean

var bool1 = new Boolean(""); // false

var bool2 = new Boolean(0); // false

var bool3 = new Boolean(undefined); // false

var bool4 = new Boolean(null); // false

var bool5 = new Boolean(NaN); // false

var bool6 = new Boolean("some text"); // true

var bool7 = new Boolean(1); // true

Boolean Methods:

Primitive or Boolean object includes following methods.

Method Description
toLocaleString() Returns string of boolean value in local browser environment.

Example: var result = (1 > 2); result.toLocaleString(); // returns "false"
toString() Returns a string of Boolean.

Example: var result = (1 > 2); result.toString(); // returns "false"
valueOf() Returns the value of the Boolean object.

Example: var result = (1 > 2); result.valueOf(); // returns false

Points to Remember :

  1. JavaScript Boolean data type can store one of two values, true or false.
  2. Boolean objects can be created using new keyword. e.g. var YES = new Boolean(true);
  3. JavaScript treats an empty string (""), 0, undefined and null as false. Everything else is true.
  4. Boolean methods are used to perform different tasks on Boolean values.