Powerful features in Javascript ES2015: enforcing required parameters
I just read a very cool article (Understanding Default Parameters in Javascript) and my takeaway is this smart piece of code to enforce that a parameter is specified:
So all you have to do is define the isRequired function in a shared library file and then use it in any function that you write.
Are you a bit put off by the fact you can use functions as default parameters? Welcome to Javascript, a language that seems designed by Eurythmics
const isRequired = () => { throw new Error('param is required'); };
function filterEvil(array, evil = isRequired()) {
return array.filter(item => item !== evil);
}
So all you have to do is define the isRequired function in a shared library file and then use it in any function that you write.
Are you a bit put off by the fact you can use functions as default parameters? Welcome to Javascript, a language that seems designed by Eurythmics
Comments
Be the first to post a comment