Skip to content

Instantly share code, notes, and snippets.

@adyngom
Last active September 26, 2017 13:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adyngom/1195c6de2389b311661712b5064804e4 to your computer and use it in GitHub Desktop.
Save adyngom/1195c6de2389b311661712b5064804e4 to your computer and use it in GitHub Desktop.
Javascript ES6 function with required arguments example
const throwIfMissing = (p) => { throw new Error(`Missing parameter: ${p}`); }
function famTree(dad = throwIfMissing("dad"),mom = throwIfMissing("mom"),...siblings) {
console.group("Family");
console.log(`Dad: ${dad}`);
console.log(`Mom: ${mom}`);
if(siblings.length > 0) {
console.log(`Siblings: ${siblings.join()}`);
}
console.groupEnd();
}
// call famTree with no arguments
famTree(); // throws first error - Missing paremeter: dad
// call famTree with one argument
famTree("Daddy"); // throws second error - Missing paremeter: mom
//call famTree with at least two arguments and body of function will execute
famTree("Daddy", "Mommy", "Big bro", "Lil sis", "Twin bro");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment