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!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay