Convert Boolean to number: Here in this article, we learn how to convert Boolean to an integer value in JavaScript. While programming when we need to work with Yes/No, ON/OFF, or true/false values, we use Boolean datatype. As we know Boolean value is either true or false, converting to integer gives us 1 or 0 respectively. Here we going to learn 5 different ways to return Boolean as an integer in JavaScript.
5 ways to convert Boolean to number in JS
- Using Conditional (ternary) operator to convert Boolean to number
- Using JavaScript Number() function to return Boolean as integer
- Unary + operation
- Using bitwise AND operator to convert Boolean to 1 or 0.
- Using bitwise OR operator.
#1 Use Conditional (ternary) operator
Here first we declare a boolean variable IsLoggedIn and set its value as true. Now we add a button tag with an onclick event. Onclick event we call our javascript function which converts boolean to numeric using ternary operator.
HTML Markup:
<script>
var IsLoggedIn=true;
</script>
<label>Using ternary operator <label>
<input type="button" value="Convert Boolean to Number" onclick="fnConvertBooleanToNumber()" />
JavaScript code:
function fnConvertBooleanToNumber() {
var convertedBoolValue = IsLoggedIn ? 1 : 0;
alert(convertedBoolValue);
}
Output:
Here it popup an alert message, which returns 1 as an integer value.
#2 Using JavaScript Number() function
Same here we use button tag and using javascript number built-in method we transform boolean to int. JavaScript Code Convert boolean to Int is as follow:
function fnConvertBooleanToNumber(){
var convertedBoolValue = Number(IsLoggedIn);
alert(convertedBoolValue);
}
#3 Unary + operation
Here we use Unary plus operation, to convert into an int value. Basically, we add a plus sign before our boolean variable. Our JS function is as below:
function fnConvertBooleanToNumber(){
var convertedBoolValue = + IsLoggedIn ;
alert(convertedBoolValue );
}
#4 Using bitwise AND operator
Here we use the bitwise AND operator, and it gives us integer value from boolean value.
JS code is as below:
function fnConvertBooleanToNumber(){
var convertedBoolValue = IsLoggedIn & 1; // bitwise AND operator
alert(convertedBoolValue);
}
#5 Using bitwise OR operator
Last but not the least here we use the bitwise OR operator, so we can convert bool value to number in javascript
Our JS function is as written below:
function fnConvertBooleanToNumber(){
var convertedBoolValue = IsLoggedIn | 0; // bitwise OR operator
alert(convertedBoolValue);
}
Conclusion: Here in this article we learn 5 ways to convert the boolean value into an integer. If one asks me I simply prefer conditional ternary operator, what you prefer write below in the comment section.
Other Reference :
Post Comment
Your email address will not be published. Required fields are marked *