JavaScript functions with default params

javascript function optional parameter default value
javascript default value if undefined
javascript default parameters null
javascript default parameters object destructuring
javascript multiple optional parameters
default parameters java
javascript default value if null
javascript object default value

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');

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 :)

Default parameters, From ES6/ES2015, default parameters are in the language specification. function read_file(file, delete_after = false) { // Code }. just works. Reference: Default  Setting JavaScript default parameters for a function In JavaScript, a parameter has a default value of undefined . It means that if you don’t pass the arguments into the function , its parameters will have the default values of undefined .

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 );

Default Parameters in Javascript, A JavaScript function can have default parameter values. Using default function parameters, you can initialize formal parameters with default values. If you do not initialize a parameter with some value, then the default value of the parameter is undefined. foo(); JavaScript lets you assign default values to your function parameters. That way if for any reason you do not pass a certain argument to a function, the function uses or falls back to the default value. Open the file default-params.js,

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.

Set a default parameter value for a JavaScript function, In the end, it's one of those new features in JavaScript which helped me write code faster and work with cleaner function bodies. But wait, there's  Parameters of functions default to undefined However, in situations it might be useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined.

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;

Easy JavaScript Part 3: What Is a Default Parameter in a Function , It sets a default value! When the function is called without any arguments the value of fruit is set to "strawberry". If the fruit parameter is set it's  Set Default Parameter In JavaScript Function Just in case no paramter is passed to the sayHello function, you can set a default value for it. Modify the helper method sayHello as shown: Now if you try to call the helper method sayHello without a paramter it will use the default value for name parameter.

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(); // []

Clean Code with ES6 Default Parameters & Property Shorthands , Enabling default parameter values in JavaScript functions is nothing new and ES6 now includes this as a feature. This article discusses some  All the power of JavaScript destructuring can be applied to parameters. You can even combine destructuring with default parameters. arguments is a special array-like object that holds all the arguments the function was invoked with. As a better alternative to arguments, you can use the rest parameters feature.

Be careful when using || to set default values in JavaScript, Usually a function will take a set number of parameters, and require that all of them be present before it can be executed successfully. However  The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function.

Using Default Parameters in ES6, Initializing function parameters in this way will make your functions easier to read and less error-prone, and will provide default behavior for your  In the next version of JavaScript, called ECMAScript 6, you will be able to set default values for parameters inside the function head. function welcome(yourName = “friend”) { document.write(“Hello,” + yourName); } EMCAScript 6 isn’t yet supported in every browser.

How To Create Default Parameters for Functions, In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter. In the example above, anotherFunction() is called every time showMessage() is called without the text parameter.

Comments
  • Do you have any questions or comments or did one of our answers help you? Feedback on or accepting an answer is appreciated.
  • Nope, that part is ok. What it does is evaluate the value of "e" if it is true, its value is assigned else the right part will evaluate to true and then be used as the value to assign.