Explain Codes LogoExplain Codes Logo

Convert boolean result into number/integer

javascript
type-coercion
truthy-falsy-values
conditional-statements
Anton ShumikhinbyAnton Shumikhin·Dec 26, 2024
TLDR

To convert a boolean to a number, use the unary + operator or the Number function:

let num = +true; // 1 (truth decoded) num = +false; // 0 (zero lies detected) num = Number(true); // 1 (truth meter: full) num = Number(false); // 0 (truth meter: empty)

+ turns true to 1, false to 0. The Number() function accomplishes the same thing.

Diverse methods for conversion

Conditional conversion: using ternary operator

Something more explanatory? Use a ternary operator:

let myNum = myBool ? 1 : 0; // incognito mode, mission: boolean conversion

myBool stands for the boolean you want to convert. If myBool is true, myNum becomes 1. If false, 0 it is!

Performance scenario: bitwise OR for integer output

In performance-centric cases such as asm.js, bitwise operators come out to play:

let myResult = true | 0; // 1 (not a bitwise vampire!) myResult = false | 0; // 0 (drained by the bitwise vampire!)

Here, | 0 ensures your result remains an integer garage rockstar, and can speed up code execution in some JavaScript engines.

Wrinkles to iron out: sanitizing inputs and handling anomalies

As responsible devs, always sanitize and validate user inputs on the server side to keep the gremlins away (unauthorized input). In type conversion, train yourself to anticipate strange climates (atypical inputs) and craft your code to handle them gracefully. You'll be securing your code like a pro!

Edge cases: prepping for the unpredictable

Null and undefined: what then?

So what happens when your boolean, isn't...messing around with null or undefined?

+null; // 0 (Null's secret identity revealed...it's zero!) +undefined; // NaN (Undefined is NaN's alter ego!)

This is courtesy of JavaScript's loose typing — a quirky superhero with just as quirky sidekicks. Always stay on guard for a twist in the tale!

Coercion spotted: dealing with truthy and falsy values

In realms where type coercion creeps in, remember, JavaScript has an expanded truth universe:

+!!'non-empty string'; // 1 (Truthy strings, assemble!) +!!''; // 0 (Empty strings, dissemble!)

Being well-versed with truthy and falsy values will help you fend off bugs that dress up in implicit type coercion costumes.

Assignments and using conversion results

When assigning the result of a conversion or using it in another expression, clarity counts:

let isActiveNumeric = +isActive; let itemQuantity = isActiveNumeric * someItem;

Thus, we first convert isActive, then use it for a multiplication: a clear script for happy debugging later!