Open In App

Convert Boolean Result into Number/Integer in JavaScript

Last Updated : 08 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

A JavaScript boolean represents one of two values: true or false. However, if one wants to convert a variable that stores a boolean value, into an integer "0" or "1", they can do so using multiple approaches.

Below are the approaches to convert a boolean to a number/integer in JavaScript:

Using ternary or conditional operator

This JavaScript code initializes a boolean variable boolvalue as true. It then uses a ternary operator to convert boolvalue into a number (1 for true, 0 for false), assigning the result to numberValue. Finally, it outputs the numeric value to the console.

Syntax:

let i = value ? 1 : 0;

Example: This example shows the implementation of the above-mentioned approach.



Output
The number value of the variable is: 1

Using unary + operator

This JavaScript code initializes a boolean variable boolvalue as true. The function myFunction converts this boolean to a number using the unary plus operator (+). It then logs the numeric value to the console. Calling myFunction() outputs 1, the numeric representation of true.

Syntax:

let i = + boolvalue;

Example: This example shows the implementation of the above-mentioned approach.


Output
The value of the variable is now: 1

Using bitwise And (&) or bitwise Or ( | ) operator

This JavaScript code initializes two boolean variables: boolvalue as true and boolvalue2 as false. The myFunction converts these booleans to numbers using bitwise operators—& for boolvalue (resulting in 1) and | for boolvalue2 (resulting in 0). The results are logged to the console.

Syntax:

let i = boolvalue & 1; // bitwise and
letj  = boolvalue | 0; // bitwise or

Example: This example shows the implementation of the above-mentioned approach.


Output
The value of variable 1 is now: 1
The value of variable 2 is now: 0

Using Number() function

This JavaScript code initializes a boolean variable boolvalue as true. The myFunction converts this boolean to a number using the Number() function, resulting in 1. The function logs the numeric value to the console.

Syntax:

let i = Number(boolvalue);

Example: This example shows the implementation of the above-mentioned approach.


Output
The value of the variable is now: 1

Next Article

Similar Reads