Skip to content

Instantly share code, notes, and snippets.

@phatnguyenuit
Created September 27, 2019 15:59
Show Gist options
  • Save phatnguyenuit/b00f29e391502c911a2253c71c3a2d99 to your computer and use it in GitHub Desktop.
Save phatnguyenuit/b00f29e391502c911a2253c71c3a2d99 to your computer and use it in GitHub Desktop.
Enforce required parameters for functions
/**
Enforce required params for functions
@author Tauqeer Awan
*/
// Define a function and throw an error from it
const isRequiredParameter = parameterName => {
throw new Error(`Missing parameter ${parameterName}`);
}
// Define a new function and use isRequiredParameter as default value
const mul = (a = isRequiredParameter('a'), b = isRequiredParameter('b')) => a * b;
// Now test your function
// This will not throw any error
mul(1, 2); // returns 2
mul(1) // throws error -> Missing parameter b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment