Q. Which is more READABLE ?
const emptyValue = "";
Boolean(emptyValue);
// false
VS
const emptyValue = "";
emptyValue ? true : false;
// false
This is a very common case in which you want the flow changes according to a specific value of a variable. I know this has almost no difference in a matter of performance, but I'm really curious about the option of the community in a matter of READABILITY.
In my opinion is more readable the second, namely:
const emptyValue = "";
emptyValue ? true : false;
but the javascript way to convert in a Boolean type is:
const emptyValue = "";
!!emptyValue;
! calls Boolean() behind the hood, thereby is called twice and is less efficient than the single Boolean() solution, but I repeat is the javascript way.
I prefer just to test the variable name
It works for ALL except 0 if you need to test a number - for that you can use !! Double Not
It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the "truthyness" or "falsyness" of the value
const emptyValue = "";
let undefinedValue;
const zero = 0;
const nullValue = null
const definedVariable = "Hello"
console.log(definedVariable,emptyValue,undefinedValue,zero,nullValue)
console.log(Boolean(definedVariable), Boolean(emptyValue),Boolean(undefinedValue),Boolean(zero),Boolean(nullValue))
console.log(!!definedVariable ,!!emptyValue,!!undefinedValue,!!zero,!!nullValue)
if (definedVariable) console.log("definedVariable is truthy");
if (!emptyValue) console.log("emptyValue is falsy");
if (!undefinedValue) console.log("undefinedValue is falsy");
if (!zero) console.log("zero is falsy");
if (!!zero) console.log("zero is not falsy with !!");
if (!nullValue) console.log("nullValue is falsy");