Exercise 5: Truthy/Falsy: Is Field Filled?

Problem Statement

Function `isFilled(value)` banao jo true tab return kare jab value meaningful ho: - string: trimmed length > 0 - number: finite - boolean: true - others: false

Sample Output:

isFilled("hello") => true
isFilled("  ") => false
isFilled(5) => true
isFilled(NaN) => false

Solution

const isFilled = (v) => {
  if (typeof v === 'string') return v.trim().length > 0;
  if (typeof v === 'number') return Number.isFinite(v);
  if (typeof v === 'boolean') return v === true;
  return false;
};

Explanation

Overall Goal:

  • Kisi bhi value ko check karna ki wo "meaningful" hai ya nahi.
  • Different types ke liye different rules: string, number, boolean.

Line 1: Function header

  • const isFilled = (v) => { → function jo kisi bhi value ko check karega.

Line 2: String check

  • if (typeof v === 'string') return v.trim().length > 0;
  • typeof v === 'string' → type check: kya value string hai?
  • Agar string hai:
  • v.trim() → extra spaces remove.
  • .length > 0 → kya trimmed string me kuch hai?
  • Example: " " → trim → "" → length 0 → false.
  • Example: "hello" → trim → "hello" → length 5 → true.

Line 3: Number check

  • if (typeof v === 'number') return Number.isFinite(v);
  • typeof v === 'number' → type check: kya value number hai?
  • Number.isFinite(v) → kya ye valid finite number hai?
  • 5, -10, 3.14true (valid).
  • NaN, Infinity, -Infinityfalse (invalid).

Line 4: Boolean check

  • if (typeof v === 'boolean') return v === true;
  • typeof v === 'boolean' → type check: kya value boolean hai?
  • v === true → sirf true hi meaningful hai, false nahi.
  • truetrue (filled).
  • falsefalse (not filled).

Line 5: Default case

  • return false; → agar koi bhi type match nahi hui (null, undefined, object, etc.) → false.

Real world:

  • Form validation: input fields ko check karna ki wo filled hain ya nahi.
  • API responses: data meaningful hai ya empty/null hai.
  • Settings: user ne value set ki hai ya default hai.