Recently we observed that our JavaScript code was not working as expected.
Now when we write conditions in JavaScript, it’s natural to want to check if a variable equals one of multiple values. A common mistake is to write the condition like this:
if (loanType == (CareFeeDeferralFeesShort || CareFeeDeferralFeesLong)) {
// do something
}
At first glance, it seems like this would check if ‘loanType’ is equal to either ‘CareFeeDeferralFeesShort’ or ‘CareFeeDeferralFeesLong’`’. Unfortunately, that’s not what JavaScript actually does.
The ‘||’ operator in JavaScript doesn’t return a boolean. Instead, it returns the first truthy value it encounters.
For example:
console.log(1 || 2); // 1
console.log(0 || 2); // 2
So in our case:
If ‘CareFeeDeferralFeesShort’ is ‘1’, then ‘(CareFeeDeferralFeesShort || CareFeeDeferralFeesLong)’ becomes ‘1’.
If it’s ‘0’ (falsy), then the expression becomes ‘CareFeeDeferralFeesLong’.
This means the condition effectively reduces to checking only one value, not both.
The right way is to compare the variable separately against both values:
if (loanType == CareFeeDeferralFeesShort ||
loanType == CareFeeDeferralFeesLong) {
// do something
}
Here, JavaScript evaluates each equality independently:
‘loanType == CareFeeDeferralFeesShort’
‘loanType == CareFeeDeferralFeesLong’
If either is true, the whole condition passes.
Takeaway
(x == (a || b)) is not the same as `x == a || x == b`.
Hope it helps..



























