Understanding Boolean in JavaScript

In JavaScript, a boolean is a basic (primitive) data type. It can only have two values:

  • true (yes)

  • false (no)

Booleans are used to control the flow of a program, especially in conditions like if, else, while, and switch.


Example: Boolean Variables

    var YES = true;
    var NO = false;

How Booleans Control Program Flow

    var YES = true;
    var NO = false;

    if (YES) {
    alert("This code block will run."); // This will happen
    }

    if (NO) {
    alert("This code block will NOT run."); // This will NOT happen
    }

 Boolean from Comparison

When you compare values, the result is always true or false.

    var a = 10, b = 20;

    var result = 1 > 2;     // false
    result = a < b;         // true
    result = a > b;         // false
    result = a + 20 > b + 5; // true

 Boolean() Function

JavaScript has a Boolean() function that converts other values to either true or false.

Returns true for:

  • Any non-zero number

  • Any non-empty string

  • An object or array

    var b1 = Boolean('Hello'); // true
    var b2 = Boolean(10);      // true
    var b3 = Boolean([]);      // true

 Returns false for:

  • 0, -0

  • null

  • false

  • NaN (Not a Number)

  • undefined

  • '' (empty string)

    var b1 = Boolean('');     // false
    var b2 = Boolean(0);      // false
    var b3 = Boolean(null);   // false

    var a;
    var b4 = Boolean(a);      // false

Boolean Object (new Boolean())

You can also create a Boolean object using new Boolean().

    var bool = new Boolean(true);
    alert(bool); // shows "true"

 But here's a trick:

Even if you create a Boolean object with false, it still acts like true in conditions!

    var bool = new Boolean(false);

    if (bool) {
    alert("This will still run!");
    }

Boolean vs Boolean Object

TypeCreated withTypeExample
boolean (primitive)true or false"boolean"typeof true ? "boolean"
Boolean (object)new Boolean()"object"typeof new Boolean(true) ? "object"



Boolean Methods

These methods can be used with booleans:

MethodWhat It DoesExample
toString()Converts boolean to "true" or "false"(1 > 2).toString(); // "false"
toLocaleString()Like toString(), but uses browser settings(1 > 2).toLocaleString(); // "false"
valueOf()Returns the real value (true or false)(1 > 2).valueOf(); // false

 



Summary

  • true and false are called booleans.

  • They're used in conditions to control what code runs.

  • Boolean() converts other types into true or false.

  • new Boolean() creates an object (be careful — even new Boolean(false) is "truthy").

  • Use typeof to check the type ("boolean" or "object").

  • Boolean values have helpful methods like toString() and valueOf().