Convert boolean result into number/integer in JavaScript
Last Updated :
02 Jul, 2019
A JavaScript boolean represents one of two values: true or false.
However, if one wants to convert a variable that stores boolean value, into integer “0” or “1”, they can do so using multiple approaches. We will look into some of them in this article.
The most popular methods are:
- Using ternary or conditional operator
- Using unary + operator.
- Using bitwise And (&) or bitwise Or ( | ) operator.
- Using Number() function. It converts data type to number.
Using ternary or conditional operator:
- Syntax:
var i = value ? 1 : 0;
- Program:
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style= "color:green" >GeeksforGeeks</h1>
<h4>Click the button to change the boolean
value into number.</h4>
<script>
var boolvalue = true
</script>
<button onclick= "myFunction()" >Change</button>
<p>The number value of the variable is :</p>
<p id= "result" ></p>
<script>
function myFunction() {
var i = boolvalue ? 1 : 0;
document.getElementById( "result" ).innerHTML = i;
}
</script>
</center>
</body>
</html>
|
- Output after clicking the button:
Using unary + operator:
- Syntax:
var i = + boolvalue;
- Program:
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style= "color:green" >GeeksforGeeks</h1>
<p>Click the button to change the boolean value.</p>
<script>
var boolvalue = true ;
</script>
<button onclick= "myFunction()" >Change</button>
<p>The value of the variable is now:</p>
<p id= "result" ></p>
<script>
function myFunction(){
var i = + boolvalue;
document.getElementById( "result" ).innerHTML = i;
}
</script>
</body>
</html>
|
-
Output after clicking the button:
Using Number() function. It converts data type to number.:
- Syntax:
var i = Number(boolvalue);
- Program:
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style= "color:green" >GeeksforGeeks</h1>
<p>Click the button to change the boolean value.</p>
<script>
var boolvalue = true ;
</script>
<button onclick= "myFunction()" >Change</button>
<p>The value of the variable is now:</p>
<p id= "result" ></p>
<script>
function myFunction(){
var i = Number(boolvalue);
document.getElementById( "result" ).innerHTML = i;
}
</script>
</body>
</html>
|
Output after clicking the button:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...