Skip to content

Instantly share code, notes, and snippets.

@azder
Created March 27, 2018 10:33
Show Gist options
  • Save azder/9f4e46ff0c669adeab5bc44713638d7f to your computer and use it in GitHub Desktop.
Save azder/9f4e46ff0c669adeab5bc44713638d7f to your computer and use it in GitHub Desktop.
Optional and mandatory values in JS functions
const mandatory = (
message => {
throw new Error(message);
}
);
function f({
optional = 'not provided',
required = mandatory('the parameter "required" must not be null or undefined'),
} = {}) {
return {
'optional is': optional,
'required is': required,
};
}
console.log(f({required: 'asdf'})); //=> { 'optional is': 'not provided', 'required is': 'asdf' }
const g = (
({
optional = 'not provided',
required = mandatory('the parameter "required" must not be null or undefined'),
} = {}) => ({
'optional is': optional,
'required is': required,
})
)
console.log(g()); //=> Error: the parameter "required" must not be null or undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment