How to convert boolean result into integer in JavaScript?
We might need this in some use cases. Converting boolean to integer is quite simple. We have multiple ways of doing it. There are some performance issues for different approaches.
Let say we have a variable in JavaScript called:
const result = true; // Requirements: if the result is true then it should be result = 1 and result = 0 in case of false
By using ternary:
let result = result ? 1 : 0;
By using unary:
+ result; // 1 when result equals true + result; // 0 when result equals false
By using expression:
result | 0; // 1 when result equals true result | 0; // 0 when result equals false
By using Number function:
Number(result); // 1 when result equals true Number(result); // 0 when result equals false