DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

3 2

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!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay