A Nifty Way to do Basic Argument Validation

A Nifty Way to do Basic Argument Validation

ยท

1 min read

Here's a clean way to validate function parameters:

    // Define an exception fn
    function throwRequiredErr() {
      throw new Error('Argument required!');
    }

    // Custom function with exception fn as default param
    function greet(person = throwRequiredErr()) {
      console.log(`Hello ${person}!`);
    }

    // Calling greet w/out arg will throw the exception
    greet(); // throwRequiredErr is called and execution pauses

    greet('Oliver'); // Logs 'Oliver'

    // Note some edge cases:
    greet(undefined); // Throws error
    greet(false); // No error
    greet(null);// No error

Essentially, we can create an exception function that we set as a default parameter to our custom function. If a person argument is supplied to our function then it will proceed as normal. However, if person is undefined, the exception fun will execute, throw the error, and pause execution.

Now no one can screw up their greeting! ๐Ÿ‘‹


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

ย