- How to convert Boolean to Number in JavaScript?
- Using the Number() Function
- Syntax
- Parameters
- Example
- Using the Bitwise Operators
- Syntax
- Example
- Using the Arithmetic Operators
- Syntax
- Example
- Преобразование типов
- Строковое преобразование
- Численное преобразование
- Логическое преобразование
- Итого
- JavaScript : Convert Boolean to Number / Integer
- 5 ways to convert Boolean to number in JS
- #1 Use Conditional (ternary) operator
- #2 Using JavaScript Number() function
- #3 Unary + operation
- #4 Using bitwise AND operator
- #5 Using bitwise OR operator
How to convert Boolean to Number in JavaScript?
In this tutorial, we will convert Boolean to Number in JavaScript. The Boolean is the variable’s data type, which is supported by JavaScript like the other programming languages.
The Boolean data type contains only two values, true and false. In some cases, programmers must convert the true or false value to the number. For example, using the strict equality operator to compare the Boolean value with the number variable.
Here, using different operators, we have three methods to convert the Boolean to a number.
Using the Number() Function
In JavaScript, the Number() function is useful to convert any variable to a number. We can also use it to convert the Boolean variables to numbers.
Syntax
Users can follow the syntax below to convert the Boolean to a number.
let bool = true; let result = Number(bool);
Parameters
Example
In the below example, we have converted the true and false both Boolean values to the number using the Number()function of JavaScript number library. The Number()function returns 1 for the true value and 0 for the false value.
html> head> /head> body> h2>Convert the Boolean to number in JavaScript./h2> h4>Convert the Boolean ( true / false ) respectively to number using i> Number() /i> function./h4> div id="number1">/div> div id = "number2">/div> /body> script> var number1 = document.getElementById("number1"); var number2 = document.getElementById("number2"); let bool = true; let result = Number(bool); number1.innerHTML = result; number2.innerHTML = Number(false); /script> /html>
Using the Bitwise Operators
In this section, we will learn to convert the Boolean to a Number using the Bitwise OR and Bitwise AND operators. When we perform the Bitwise OR operation of Boolean value with 0, it returns the number value.
Furthermore, when the user performs the Bitwise AND operation of 1 with any Boolean values, it returns a respected number value.
Syntax
Users can follow the syntax below to convert the Boolean to a number using Bitwise operators.
let bool = true; let result = bool | 0; // using the Bitwise OR operator let result = bool & 1; // using the Bitwise AND operator
Example
In the example below, we have taken two different examples of converting Boolean tonumber, one is using the Bitwise | operator and another is using the Bitwise & operator.
html> head> /head> body> h2>Convert the Boolean to number in JavaScript./h2> h4>Converting the Boolean true to number using i> Bitwise | /i> operator./h4> div id = "number1">/div> h4>Converting the Boolean false to number using i> Bitwise &/i> operator./h4> div id = "number2">/div> /body> script> var number1 = document.getElementById("number1"); var number2 = document.getElementById("number2"); let bool = true; let result = bool | 0; number1.innerHTML = result; bool = false; number2.innerHTML = bool & 1; /script> /html>
Using the Arithmetic Operators
This is the last approach of this tutorial to convert the Boolean to a number. We will use the addition and multiplication, arithmetic operator. However, we can also use the subtraction and division operators.
When we add or subtract the 0 from the Boolean value, it returns the number value respected to the Boolean value. And the same way, when we multiply the Boolean value by 1, it returns the same result as the addition.
Syntax
Follow the syntax below to use multiplication and addition operators.
let bool = true; let result = bool + 0; // using the Arithmetic + operator let result = bool * 1; // using the Arithmetic * operator
Example
In the example below, we have used the addition and multiplication operators to convert the Boolean to a number.
html> head> /head> body> h2>Convert the Boolean to number in JavaScript./h2> h4>Convert the Boolean false to number using i> Arithmetic + /i> operator./h4> div id = "number1">/div> h4>Convert the Boolean true to number using i> Arithmetic * /i> operator./h4> div id = "number2">/div> /body> script> var number1 = document.getElementById("number1"); var number2 = document.getElementById("number2"); let bool = false; let result = bool + 0; number1.innerHTML = result; bool = true; number2.innerHTML = bool * 1; /script> /html>
Users can use any of three methods to convert Boolean to Integer. The first method calls the built-in library function, which is slower than the second and third approaches. In any programming language, Bitwise operation is the fastest operation. So, the second method is the fastest approach, and users can use it easily.
Преобразование типов
Чаще всего операторы и функции автоматически приводят переданные им значения к нужному типу.
Например, alert автоматически преобразует любое значение к строке. Математические операторы преобразуют значения к числам.
Есть также случаи, когда нам нужно явно преобразовать значение в ожидаемый тип.
В этой главе мы не касаемся объектов. Сначала мы разберём преобразование примитивных значений.
Мы разберём преобразование объектов позже, в главе Преобразование объектов в примитивы.
Строковое преобразование
Строковое преобразование происходит, когда требуется представление чего-либо в виде строки.
Например, alert(value) преобразует значение к строке.
Также мы можем использовать функцию String(value) , чтобы преобразовать значение к строке:
let value = true; alert(typeof value); // boolean value = String(value); // теперь value это строка "true" alert(typeof value); // string
Преобразование происходит очевидным образом. false становится «false» , null становится «null» и т.п.
Численное преобразование
Численное преобразование происходит в математических функциях и выражениях.
Например, когда операция деления / применяется не к числу:
alert( "6" / "2" ); // 3, строки преобразуются в числа
Мы можем использовать функцию Number(value) , чтобы явно преобразовать value к числу:
let str = "123"; alert(typeof str); // string let num = Number(str); // становится числом 123 alert(typeof num); // number
Явное преобразование часто применяется, когда мы ожидаем получить число из строкового контекста, например из текстовых полей форм.
Если строка не может быть явно приведена к числу, то результатом преобразования будет NaN . Например:
let age = Number("Любая строка вместо числа"); alert(age); // NaN, преобразование не удалось
Правила численного преобразования:
Значение | Преобразуется в… |
---|---|
undefined | NaN |
null | 0 |
true / false | 1 / 0 |
string | Пробельные символы (пробелы, знаки табуляции \t , знаки новой строки \n и т. п.) по краям обрезаются. Далее, если остаётся пустая строка, то получаем 0 , иначе из непустой строки «считывается» число. При ошибке результат NaN . |
alert( Number(" 123 ") ); // 123 alert( Number("123z") ); // NaN (ошибка чтения числа на месте символа "z") alert( Number(true) ); // 1 alert( Number(false) ); // 0
Учтите, что null и undefined ведут себя по-разному. Так, null становится нулём, тогда как undefined приводится к NaN .
Большинство математических операторов также производит данное преобразование, как мы увидим в следующей главе.
Логическое преобразование
Логическое преобразование самое простое.
Происходит в логических операциях (позже мы познакомимся с условными проверками и подобными конструкциями), но также может быть выполнено явно с помощью функции Boolean(value) .
- Значения, которые интуитивно «пустые», вроде 0 , пустой строки, null , undefined и NaN , становятся false .
- Все остальные значения становятся true .
alert( Boolean(1) ); // true alert( Boolean(0) ); // false alert( Boolean("Привет!") ); // true alert( Boolean("") ); // false
Некоторые языки (к примеру, PHP) воспринимают строку «0» как false . Но в JavaScript, если строка не пустая, то она всегда true .
alert( Boolean("0") ); // true alert( Boolean(" ") ); // пробел это тоже true (любая непустая строка это true)
Итого
Существует 3 наиболее широко используемых преобразования: строковое, численное и логическое.
Строковое – Происходит, когда нам нужно что-то вывести. Может быть вызвано с помощью String(value) . Для примитивных значений работает очевидным образом.
Численное – Происходит в математических операциях. Может быть вызвано с помощью Number(value) .
Преобразование подчиняется правилам:
Значение | Становится… |
---|---|
undefined | NaN |
null | 0 |
true / false | 1 / 0 |
string | Пробельные символы по краям обрезаются. Далее, если остаётся пустая строка, то получаем 0 , иначе из непустой строки «считывается» число. При ошибке результат NaN . |
Логическое – Происходит в логических операциях. Может быть вызвано с помощью Boolean(value) .
Значение | Становится… |
---|---|
0 , null , undefined , NaN , «» | false |
любое другое значение | true |
Большую часть из этих правил легко понять и запомнить. Особые случаи, в которых часто допускаются ошибки:
- undefined при численном преобразовании становится NaN , не 0 .
- «0» и строки из одних пробелов типа » » при логическом преобразовании всегда true .
В этой главе мы не говорили об объектах. Мы вернёмся к ним позже, в главе Преобразование объектов в примитивы, посвящённой только объектам, сразу после того, как узнаем больше про основы JavaScript.
JavaScript : Convert Boolean to Number / Integer
Convert the Boolean to Int: 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 an integer gives us 1 or 0 respectively. Here we going to learn 5 different ways to return the Boolean results as an integer value in JavaScript.i.e ( In js boolean to int conversion)
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.
Using ternary operator
function fnConvertBooleanToNumber()
Here it popup an alert message, which returns 1 as an integer value.
#2 Using JavaScript Number() function
Same here we use a button tag and using the javascript built-in Number() method we transform boolean to an integer. JavaScript Code Convert boolean to number is as follow:
function fnConvertBooleanToNumber()
#3 Unary + operation
Here we use the Unary plus operation, to convert it into an integer value. Basically, we add a plus sign before our boolean variable, and with this single line code, we achieve bool to int js conversion.
Our JS function is as below:
function fnConvertBooleanToNumber()
#4 Using bitwise AND operator
Here we use the bitwise AND operator, and it gives us numeric value from the boolean result. As you see with this simple javascript code we able to convert boolean to number.
function fnConvertBooleanToNumber() < var convertedBoolValue = IsLoggedIn & 1; // bitwise AND operator alert(convertedBoolValue); >
#5 Using bitwise OR operator
Last but not 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 value (number). If one asks me I simply prefer conditional ternary operator, what you prefer write below in the comment section.
Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.
PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee
Subscribe to our newsletter
Get the latest and greatest from Codepedia delivered straight to your inbox.
Your email address will not be published. Required fields are marked *