Booleans JS Home  <<  JS Basics  <<  Booleans

Booleans are created using the global object constructor Boolean or exist in the form of the boolean primitives true and false.

The Boolean constructor is a wrapper for a boolean value and should not be confused with the true and false values of the Boolean primitives.

There are a some things to remember when creating Boolean objects and how the parameter passed to the Boolean constructor is converted to a boolean value:

  • If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (''), the object has an initial value of false.
  • Any other values, including objects and the string 'false' create an object with an initial value of true.
  • Any values other than undefined and null evaluate to true when passed to a conditional statement.

The code below highlights the difference between the Boolean constructor and boolean primitives true and false.

// Create a Boolean Object.
aBoolean = new Boolean(false);

if (aBoolean) {
  alert('set false, but evaluates true - Boolean Object'); // Executed
} else {
  alert('set false - Boolean Object'); // NOT executed

// Set a boolean primitive.
bBoolean = false;

if (bBoolean) {
  alert('set false, but evaluates true - boolean primitive'); // NOT executed
} else {
  alert('set false - boolean primitive'); // Executed

Press the button below to action the above code:

Reviewing The Code

Use the boolean primitives true and false when using conditional statements, and the Boolean constructor when you just want to wrap a boolean value.

Lesson 9 Complete

In this last lesson in the basics section of the site for JavaScript we looked at booleans and some of their uses..


JavaScript Reference - Boolean constructor
JavaScript Reference - new special operator