How to convert a Boolean to Integer in JavaScript?

In JavaScript, you can convert a Boolean to an integer using several methods. The most common approaches are the ternary operator, the Number() constructor, and the unary plus operator.

Method 1: Using the Ternary Operator

The ternary operator provides explicit control over the conversion values:

<html>
   <head>
      <title>Boolean to Integer Conversion</title>
   </head>
   <body>
      <script>
         var answer = true;
         console.log("Boolean value:", answer);

         var pass_marks = answer ? 90 : 40;
         console.log("Passing Marks:", pass_marks);

         // Converting false
         var failed = false;
         var fail_marks = failed ? 90 : 40;
         console.log("Failed Marks:", fail_marks);
      </script>
   </body>
</html>
Boolean value: true
Passing Marks: 90
Failed Marks: 40

Method 2: Using Number() Constructor

The Number() function converts Boolean values directly to 0 or 1:

<html>
   <head>
      <title>Number() Conversion</title>
   </head>
   <body>
      <script>
         console.log("true to integer:", Number(true));
         console.log("false to integer:", Number(false));
         
         var isActive = true;
         var status = Number(isActive);
         console.log("Status code:", status);
      </script>
   </body>
</html>
true to integer: 1
false to integer: 0
Status code: 1

Method 3: Using Unary Plus Operator

The unary plus (+) operator is a shorthand for Number() conversion:

<html>
   <head>
      <title>Unary Plus Conversion</title>
   </head>
   <body>
      <script>
         var isLoggedIn = true;
         var notLoggedIn = false;
         
         console.log("Logged in status:", +isLoggedIn);
         console.log("Not logged in status:", +notLoggedIn);
         
         // Using in expressions
         var totalUsers = +isLoggedIn + +notLoggedIn;
         console.log("Total boolean count:", totalUsers);
      </script>
   </body>
</html>
Logged in status: 1
Not logged in status: 0
Total boolean count: 1

Comparison

Method true ? Result false ? Result Use Case
Ternary Operator Custom value Custom value When you need specific integer values
Number() 1 0 Standard binary conversion
Unary Plus (+) 1 0 Quick binary conversion

Conclusion

Use the ternary operator for custom integer values, Number() or unary plus (+) for standard 1/0 conversion. The unary plus operator is the most concise for simple Boolean-to-binary conversion.

Updated on: 2026-03-15T23:18:59+05:30

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements