29047

JavaScript functions with default params

I currently use the following function which checks the three params to see if there are any passed through, is this the best way to do this whilst setting a default if no parameter has been sent?

function setupSlideshow(t, e, s) { e = e || '.slideshow'; s = s || '> li'; t = t || 70; $timeout(function() { $(e).cycle({ swipe: true, slides: s, fx: 'scrollHorz', pager: '.cycle-pager', timeout: 0 }); }, t); }

By using setupSlideshow(70); this sets my timeout to 70ms but when it comes to setting the element then using setupSlideshow('.new-slideshow'); doesn't work.

setupSlideshow(70); setupSlideshow('.new-slideshow'); setupSlideshow('.new-slideshow','.slide');

Answer1:

I think you have forgot that parameters always have to be entered in order... Here your first parameter is the time in milliseconds for your timeout, and the second parameter is the slideshow element. If you ommit your time completemy, the slideshow element will be the first parameter, so be treated as your time by the function.

One way jQuery uses to counter this is the use of one option parameter. This consist of passing an object for the function to use, this would look like that:

function setupSlideshow(options) { options = options || {}; e = options.e || '.slideshow'; s = options.s || '> li'; t = options.t || 70; $timeout(function() { $(e).cycle({ swipe: true, slides: s, fx: 'scrollHorz', pager: '.cycle-pager', timeout: 0 }); }, t); } setupSlideshow({t:70}); setupSlideshow({e:'.new-slideshow'}); setupSlideshow({e:'.new-slideshow',s:'.slide'});

Using this technique is useful for this kind of usage but may become a problem maker too when too many options are possible and not well documented so keep it clean and commented :)

Answer2:

Parameters must be passed to a function in the same order that they are defined. So;

setupSlideshow('.new-slideshow');

The parameter here is being passed to the t variable in your function.

What you want to do is this:

setUpSlideshow(false, '.new-slideshow', '.slide');

this will pass false to the t variable and it will get changed to your default value.

Alternatively, you may want to consider using an 'options'/'arguments' object... :

function setupSlideshow(args) { e = e in args ? args.e : '.slideshow'; s = s in args ? args.s : '> li'; t = t in args ? args.t : 70; ... } args = { e: '.new-slideshow', s: '.slide' }; setupSlideshow( args );

Answer3:

As far as my limited JS goes, I think I've got this one.

Currently where you write e = e || '.slideshow'; you're trying to access e as a variable, however, the browser is interpreting that as an argument. Change it to the following:

var e = e || '.slideshow', s = s || '> li', t = t || 70;

Answer4:

Look at the below implementations. With the default params 'features = []' in place, the code can be made highly concise in ES6.

ES6: new

function setUserAccess(features = []){ return features; }; setUserAccess(); // []

ES5: old

function setUserAccess(features){ features = features || []; return features; }; setUserAccess(); // []

Answer5:

Old way of function with default params like this:

function x(param1, param2){ param1 = param1 || 'param1_default'; param2 = param2 || 'param2_default'; console.log(param1, param2); //etc }

Better way like this:

Using function destruction and defaults

function x({param1='param1_default', param2='param2_default'}={}){ console.log(param1, param2); //etc } x(); //returns 'param1_default', 'param2_default' x({}); //returns 'param1_default', 'param2_default' x({param1:'a'}); //returns 'a', 'param2_default' x({param1:'a', param2:'b'}); //returns 'a', 'b'

What is actually happening here is we do destructuring from argument. If no arguments provided than default one is used - which is = {}. And in that case because default empty object doesn't have fields, destructuring will take default values.

Recommend

  • How to calculate code coverage in Hudson using emma for a multi-module maven project but only run te
  • How to “convert” a plugin to a gem a make it “private”?
  • Error compiling OpenSSL for Win32
  • Regex to match a substring within 2 brackets, e.g. [i want this text] BUT leave out the brackets?
  • Subclass HashSet so that it always uses a certain IEqualityComparer when used in another set
  • Can we use tables to design a form? [closed]
  • UITableView without still works!
  • purpose of if (true)
  • Xcode 4 - Is there something in Interface Builder like “reveal in canvas”?
  • How to Count the Number of a Specific Character in a Cell with Excel VBA
  • Access textfield of UIAlertController - swift ios8
  • Static initializer inside member function require compile-time constant?
  • Determining signed state for HDF5 variables in NetCDF
  • Bind two JSF input fields with single property of backing bean
  • Cannot set password with DirectoryEntry.Invoke when user is created in AD using ASP.NET C#
  • Continuous movement of a box in pygame
  • Add new accepted protocol to URL/link validation in SharePoint 2010
  • UltraWinGrid Auto Refresh
  • WCF Service Application returns 404 using WebGet
  • Get both date and time in milliseconds
  • Angularjs: [$injector:modulerr] Failed to instantiate module ui-router
  • Determining if a string has been entered with a leading single quote
  • Type mismatch: cannot convert from Connection to Connection
  • JFreeChart heap space
  • Drag and Drop for imageview not working
  • Sed: Using a,c or i in a one-liner
  • get all processes in parallel
  • countdown bar android example
  • How VBA declared Volatility works
  • Reading JSON from a file using C++ REST SDK (Casablanca)
  • NetLogo BehaviorSpace - Measure runs using reporters
  • Spring security and special characters
  • How to handle AllServersUnavailable Exception
  • JSON with duplicate key names losing information when parsed
  • Large data - storage and query
  • jQuery tmpl and DataLink beta
  • How to disable jQuery.jplayer autoplay?
  • C# - Getting references of reference
  • CSS Applying specific rule for a specific monitor resolution with only CSS is posible?
  • Setting background image for body element in xhtml (for different monitors and resolutions)