JS Tip - Required function parameters

Javascript Ninja - Required function parameters

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 in the function call, the getter handler will be triggered and the error will be thrown.
 /**  
  * Using global property  
  */  
 Object.defineProperty(self, 'reuired', {  
  get() {  
   throw new TypeError("Missing paramter!!");  
  }  
 })  
 const foo = (bar = required) => console.log(bar)  
 foo("Hello!!") //prints Hello!!  
 foo() // will throw error  

Comments

  1. youtube_stats-scores-odds.html 5 days ago - videodl.cc
    youtube_stats-scores-odds.html 5 days ago how to convert youtube to mp3 — youtube_stats-scores-odds.html 5 days ago youtube_stats-scores-odds.html 6 days ago — youtube_stats-scores-odds.html 5 days ago

    ReplyDelete

Post a Comment

Popular posts from this blog

JS Tip - Use variable parameters for setTimeout()

Disallow specific imports in Javascript Project