Optional parameters in JavaScript [duplicate]

Better solution is to use named arguments wraped in a object. It keeps your code clean and prevents errors in case of complex functions (with many default and non-default arguments). Otherwise you need to remember about the order of arguments and assign default values based on the types of arguments present (that’s what you’re trying to do).

That method is a primary way of passing params jQuery and jQuery’s plugins.

function test(options) { 

  // set up default options 
  var defaults = { 
    param1:      'test', 
    param2:      100
  }; 

  // combine options with default values
  var options = $.extend({}, defaults, options); // If you're not using jQuery you need different function here

  alert(options.param1)
  alert(options.param2)

}

test({'param2': 200}) // Call the function with just the second param

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)