DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
JS Bits with Bill
JS Bits with Bill

Posted on • Updated on

A Nifty Way to do Basic Argument Validation

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
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)

"I made 10x faster JSON.stringify() functions, even type safe"

โ˜๏ธ Must read for JS devs