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)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay