🟑 MediumWhat's Wrong?πŸ› Debug Challenge

Wrong comparison with NaN

Buggy Code β€” Can you spot the issue?

function isInvalid(value) {
  if (value === NaN || value === undefined || value === null) {
    return true;
  }
  return false;
}

console.log(isInvalid(NaN));       // false β€” BUG!
console.log(isInvalid(undefined)); // true
console.log(isInvalid(null));      // true

Fixed Code

function isInvalid(value) {
  if (Number.isNaN(value) || value === undefined || value === null) {
    return true;
  }
  return false;
}

// Cleaner version:
const isInvalid = (value) =>
  value == null || Number.isNaN(value);
// value == null catches both null and undefined (loose equality)

console.log(isInvalid(NaN));       // true βœ“
console.log(isInvalid(undefined)); // true βœ“
console.log(isInvalid(null));      // true βœ“

Bug Explained

Bug: NaN is the only value in JS not equal to itself. value === NaN is ALWAYS false, for any value including NaN itself.

Explanation: Use Number.isNaN() to check for NaN β€” it's the only reliable method. value == null (loose equality) catches both null and undefined at once.

Key Insight: NaN !== NaN always. Use Number.isNaN(). And value == null catches both null AND undefined.

More What's Wrong? Debug Challenges

🟒 EasyAccidental global variableβ†’πŸ”΄ HardInfinite re-render in React useEffectβ†’πŸŸ‘ MediumArray sort mutates originalβ†’πŸŸ‘ MediumSpread only shallow-copies nested arraysβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab