Posts

Showing posts from March, 2020

JS Tip - Required function parameters

Image
Sometimes we need to ensure that a required parameter has been provided. This can be achieved by two easy ways - Default function parameters Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed. We can take the advantages of this ES6 feature and make a function which throws an error and assign it as default value for required parameters. So when no parameter is passed this function will be called and it will thrown an error !!! /** * Using Default function parameter */ const required = () => { throw new TypeError("Missing paramter!!"); } const foo = (bar = required()) => console.log(bar) foo("Hello!!") //prints Hello!! foo() // will throw error - Global property Another way to deal with required function parameters is to create a global property named required . It can be assigned as default function parameter, so if no value has been specified