Bird
0
0

Consider this NestJS pipe code snippet:

medium📝 Debug Q14 of 15
NestJS - Pipes
Consider this NestJS pipe code snippet:
transform(value: any) {
  const num = parseInt(value);
  if (!num) {
    throw new Error('Invalid number');
  }
  return num;
}

What is the bug in this pipe when input is '0'?
AIt throws an error incorrectly because !num is true for 0
BIt returns a string instead of a number
CIt does not parse the input at all
DIt always returns NaN
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the condition !num with input '0'

    parseInt('0') returns 0, but !0 is true in JavaScript, so the error is thrown incorrectly.
  2. Step 2: Identify the bug cause

    The check should explicitly test for NaN, not falsy values, to avoid rejecting valid 0.
  3. Final Answer:

    It throws an error incorrectly because !num is true for 0 -> Option A
  4. Quick Check:

    Falsy check fails for 0, use isNaN instead [OK]
Quick Trick: Falsy check fails for 0; use isNaN() to validate numbers [OK]
Common Mistakes:
  • Using !num to check invalid numbers
  • Ignoring 0 as a valid number
  • Not testing for NaN explicitly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes