JavaScript: Utility function to default function in parameters

Recently I came across a interesting discussion on reddit. And that was about a utility function which will give you flexibility to define default function in parameters.

I found it very interesting, so wrote one for me.

in param: defaultArg1, defaultArg2, .... function
return : function 
var defaultParams = function(){
  var args = arguments,
   len = args.length,
   fn = args[--len],
   defaultArg = [];
  if(typeof fn !== 'function'){
   throw new Error('invalid arguments');
   defaultArg[len] = args[len];
  return function(){  
   var args = arguments,
    fnlen = fn.length,
    params = [];
     params[fnlen] = args[fnlen] == null ?  defaultArg[fnlen] : args[fnlen];
   return fn.apply(this, params);
//how to use 
var alert_my_age = defaultParams(21, function(age) {
alert_my_age()   //#=> Alerts 21
alert_my_age(45) //#=> Alerts 45


Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

CSS Specificity

Application Design Notes