This post will discuss how to convert a boolean value to a number in JavaScript. In other words, map the boolean values true and false to the numeric values 1 and 0, respectively.

To map a boolean true or false to the number 1 or 0 in JavaScript, we can use any of the following options:

1. Using Number() function

One of the easiest and most common ways to convert a boolean to a number in JavaScript is by using the Number() function, which converts any value to a number. Therefore, if we pass a boolean value as an argument to the Number() function, it will return 1 for true and 0 for false. Here’s an example:

Download  Run Code

2. Using unary plus operator (+)

Another way to convert a boolean to a number in JavaScript is by using the unary plus operator (+), which also converts any value to a number. If we use this operator with a boolean value, it will return 1 for true and 0 for false. Here’s an example:

Download  Run Code

3. Using bitwise operators

A third way to convert a boolean to a number in JavaScript is by using the bitwise operators, such as bitwise AND (&) or bitwise OR (|) or bitwise XOR (^), which perform operations on the binary representation of a number. If we use these operators with a boolean value, they will coerce the value to a number and return 1 for true and 0 for false. Here’s an example:

Download  Run Code

4. Using ternary operator

A fourth way to convert a boolean to a number in JavaScript is by using the ternary operator (?:), which evaluates a condition and returns one of two values depending on whether the condition is true or false. If we use this operator with a boolean value as the condition, we can return 1 for true and 0 for false. Here’s an example:

Download  Run Code

5. Using Array.indexOf() function

A fifth way to convert a boolean to a number in JavaScript is by using the Array.indexOf() function, which returns the index at which a given element is first found in the array. If we use this function with an array that contains only false and true as elements, in that order, and pass a boolean value as the argument, it will return 1 for true and 0 for false. Here’s an example:

Download  Run Code

That’s all about converting a boolean value to 0 or 1 in JavaScript.