In JavaScript you can check whether a variable has any value like this
if (strValue) {
//do something
}
Today I encountered something beyond my understanding, a conditional where I used this wasn't working as I expected. I had some JavaScript code that looked similar to below snippet.
var blnX = false;
var intX = 3;
var strX = "2021-03-25T13:53:13.259352Z";
function test(blnValue, intValue, strValue) {
return !blnValue && (intValue == 2 || ((intValue == 3 || intValue == 4) && strValue));
}
var result = test(blnX, intX, strX);
At this point I expected result to be true but it contained "2021-03-25T13:53:13.259352Z".
When I change the return statement like below,
return (((intValue == 3 || intValue == 4) && strValue) || intValue == 2) && !blnValue;
or like this,
return !blnValue && (intValue == 2 || (strValue && (intValue == 3 || intValue == 4)));
then it does return true.
To make it even more confusing when I change the function from the above snippet like below, then it does work like expected.
function test(blnValue, intValue, strValue) {
if (!blnValue && (intValue == 2 || ((intValue == 3 || intValue == 4) && strValue)))
return true;
return false;
}
Can someone explain to me why the conditional from the return statement used in the first function is not returning the expected boolean value?
0or""(empty string) are falsy values.