Skip to content

Instantly share code, notes, and snippets.

@martinhj
Created April 29, 2019 09:24
Show Gist options
  • Save martinhj/d9aea76693c04af48e0f7421edb13002 to your computer and use it in GitHub Desktop.
Save martinhj/d9aea76693c04af48e0f7421edb13002 to your computer and use it in GitHub Desktop.
Elegant throw error on missing argument
// From https://davidwalsh.name/javascript-tricks
/**
Those three dots made the task so much easier!
Require Function Parameters
Being able to set default values for function arguments was an awesome addition to JavaScript, but check out this trick for requiring values be passed for a given argument:
*/
const isRequired = () => { throw new Error('param is required'); };
const hello = (name = isRequired()) => { console.log(`hello ${name}`) };
// This will throw an error because no name is provided
hello();
// This will also throw an error
hello(undefined);
// These are good!
hello(null);
hello('David');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment