
Recently, while debugging my codebase, I encountered a surprising issue: An the if condition wasn’t working as expected, even though the logic looked perfectly fine.
The Code Like:
//Javascript
let a = ['IN', 'UP'];
let b = [];
let c = [];
if (b != '' && c != '') {
// Expected to be true
console.log('Condition passed');
} else {
}
Expectation: Both b and c are arrays — and not empty strings, so the condition should pass.
❌ Reality: The condition failed — why?
Root Cause: JavaScript Type Coercion with !=
How to Fix It: Use proper array checks:
javascript
if (Array.isArray(b) && b.length > 0 && Array.isArray(c) && c.length > 0) {
console.log('Both arrays are non-empty');
}
Takeaway:
Don’t use loose equality (==, !=) when checking for empty arrays or strings. Use .length, Array.isArray(), and strict comparisons (===, !==) to avoid silent bugs.