Before getting into the details, here we are using VS Code to write JavaScript code.
How to convert a Boolean into a number in JavaScript
This section provides the usage of various functions and operators that will be used to convert a Boolean into a number in JavaScript.
How to use Unary operator to convert a Boolean to a number in JavaScript
The unary operator is just prefixing a “+” sign to a Boolean value and the Boolean value will be converted to the respective number. The Unary operation is carried out using the following syntax:
Syntax
For instance, the following code converts false and true Boolean values to relevant numbers:
Code
console.log(n); // printing the n variable
var m = +false; // storing the +false in m variable
console.log(m); // printing the m variable
Output
How to use Ternary operator to convert a Boolean to a number in JavaScript
The ternary operator (?) is used by following the syntax provided below:
Syntax
The following line of code uses the ternary operator to convert false and true to 0 and 1 respectively:
Code
console.log(q); //printing the q variable
var w = false ? 1:0; //declaring w variable
console.log(w); //printing the w variable
Output
How to use Number() function to convert a Boolean to a number in JavaScript
The Number() function can be used to convert a Boolean value to a number, and it works on the basis of following syntax:
Syntax
The code provided below shows that Boolean value is passed to convert it to a number:
Code
Output
How to use Arithmetic Operators to convert Boolean to a number in JavaScript
Interestingly, the arithmetic operators can also be used to convert a Boolean to a number in JavaScript.
Using * to convert a Boolean to a number
The syntax provided below converts the Boolean to number:
The following lines of code converts the Boolean value “False” to respective number (0) and “True” to “1”:
Code
console.log(a); //printing the a variable
var s =true*1; //declaring s variable
console.log(s); //printing the s variable
Output
Using + to convert a Boolean into a number
To convert a Boolean into a number using + operator, you have to use “0” with that Boolean value: We have practiced “+” to convert Boolean to a number as shown below:
console.log(d); //printing the d variable
var f =true+0; //declaring f variable
console.log(f); //printing the f variable
Output
Conclusion
JavaScript provides support of various functions and operators to convert a Boolean into a number. This article contains the functionality of the Number() function, and operators such as AND, OR, Unary, Ternary and Arithmetic. All these operators and functions are used to convert a Boolean into a number. A Boolean number has value True/ON and False/OFF; therefore, when a Boolean is converted into a number it would return 1 or 0 for True/ON or False/OFF respectively.