How to declare boolean variables in JavaScript?

A boolean variable in JavaScript has two values: true or false. Boolean values are essential for conditional logic, comparisons, and control flow in JavaScript applications.

Syntax

let variableName = true;   // or false
let variableName = Boolean(value);  // converts value to boolean

Direct Boolean Assignment

The simplest way to declare boolean variables is by directly assigning true or false:

<!DOCTYPE html>
<html>
<body>
   <p>Boolean variable examples:</p>
   <button onclick="showBooleans()">Show Boolean Values</button>
   <p id="result"></p>

   <script>
      function showBooleans() {
         let isActive = true;
         let isComplete = false;
         
         document.getElementById("result").innerHTML = 
            "isActive: " + isActive + "<br>" +
            "isComplete: " + isComplete;
      }
   </script>
</body>
</html>

Boolean from Comparisons

Boolean values are often created through comparison operations:

<!DOCTYPE html>
<html>
<body>
   <p>35 > 20</p>
   <button onclick="myValue()">Click for result</button>
   <p id="test"></p>
   
   <script>
      function myValue() {
         let result = 35 > 20;
         document.getElementById("test").innerHTML = 
            "Result: " + result + " (type: " + typeof result + ")";
      }
   </script>
</body>
</html>

Using Boolean() Constructor

The Boolean() function converts other values to boolean:

<!DOCTYPE html>
<html>
<body>
   <button onclick="testBoolean()">Test Boolean Conversion</button>
   <p id="conversion"></p>

   <script>
      function testBoolean() {
         let results = [
            "Boolean(1): " + Boolean(1),
            "Boolean(0): " + Boolean(0),
            "Boolean('hello'): " + Boolean('hello'),
            "Boolean(''): " + Boolean(''),
            "Boolean(null): " + Boolean(null)
         ];
         
         document.getElementById("conversion").innerHTML = results.join("<br>");
      }
   </script>
</body>
</html>

Falsy and Truthy Values

Falsy Values Truthy Values
false, 0, "", null, undefined, NaN Everything else (non-empty strings, non-zero numbers, objects, arrays)

Conclusion

Boolean variables are declared using true/false literals, comparison operations, or the Boolean() constructor. Understanding truthy and falsy values is crucial for effective boolean usage in JavaScript.

Updated on: 2026-03-15T21:26:20+05:30

703 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements