javascriptif-statementvariablestruthinessecmascript-2020

Checking lots of variables for truthiness in a single pass


I have a large form with many fields and a special processing function
Several variables of different types declared at the beginning of a function

I would like to check that a user has set all variables before a function execution

const a1 = true, a2 = "str", a3 = { b: true }, a4 = [], a5 = "";

// Variant 1: old school
if (!(a1 && a2 && a3 && a4 && a5))
  return toast.error('Please fill out all fields');

// Variant 2: array aggregation
if (!Array.of(a1, a2, a3, a4, a5).every(Boolean))
  return toast.error('Please fill out all fields');

I would like to catch a5, since it's an empty string

Variant 1 is not readable if we have 5+ variables and not very elegant
Variant 2 is more elegant and clear but doesn't work for variables of not type Boolean

How do you check lots of variables in one pass?


Solution

  • Would that work for you?

    const hasTruthyInput = v => typeof v === 'string' ? v.trim().length > 0 : Boolean(v);
    
    // Variant 2: array aggregation
    if (!Array.of(a1, a2, a3, a4, a5).every(hasTruthyInput))
      return toast.error('Please fill out all fields');
    

    I used v.trim() to make it harder for the user to circumvent the form by entering a string full of whitespaces. Adjust to your needs.