javascript tutorial - [Solved-5 Solutions] Set a default parameter value for a javascript function - javascript - java script - javascript array



Problem:

We would like a JavaScript function to have optional arguments which we set a default on, which gets used if the value isn't defined. In Ruby we can do it like this:

def read_file(file, delete_after = false)
  # code
end
click below button to copy the code. By JavaScript tutorial team

Does this work in JavaScript?

function read_file(file, delete_after = false) {
  // Code
}

click below button to copy the code. By JavaScript tutorial team

Solution 1:

From ES6/ES2015, default parameters is in the language specification.

function read_file(file, delete_after = false) {
  // Code
}
click below button to copy the code. By JavaScript tutorial team

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. We can also simulate default named parameters via destructuring:

// the `= {}` below lets we call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
    // Use the variables `start`, `end` and `step` here
    ···
}
click below button to copy the code. By JavaScript tutorial team

There are a lot of ways, but this is my preferred method - it lets we pass in anything we want, including false or null.

(typeof null == "object")
function foo(a, b)
{
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}

click below button to copy the code. By JavaScript tutorial team

Solution 2:

function read_file(file, delete_after) {
    delete_after = delete_after || "my default here";
    //rest of code
}
click below button to copy the code. By JavaScript tutorial team

This assigns to delete_after the value of delete_after if it is not a falsey value otherwise it assigns the string "my default here". For more detail, check out Doug Crockford's survey of the language and check out the section on Operators .

This approach does not work if we want to pass in a falsey value i.e. false, null, undefined, 0 or "".

When dealing with a number of parameters to a function, it is often useful to allow the consumer to pass the parameter arguments in an object and then merge these values with an object that contains the default values for the function

function read_file(values) {
    values = merge({ 
        delete_after : "my default here"
    }, values || {});

    // rest of code
}

// simple implementation based on $.extend() from jQuery
function merge() {
    var obj, name, copy,
        target = arguments[0] || {},
        we = 1,
        length = arguments.length;

    for (; we < length; i++) {
        if ((obj = arguments[i]) != null) {
            for (name in obj) {
                copy = obj[name];

                if (target === copy) {
                    continue;
                }
                else if (copy !== undefined) {
                    target[name] = copy;
                }
            }
        }
    }

    return target;
};
to use
// will use the default delete_after value
read_file({ file: "my file" }); 

// will override default delete_after value
read_file({ file: "my file", delete_after: "my value" });
click below button to copy the code. By JavaScript tutorial team

Solution 3:

WE find something simple like this to be much more concise and readable personally.

function pick(arg, def) {
   return (typeof arg == 'undefined' ? def : arg);
}

function myFunc(x) {
  x = pick(x, 'my default');
} 

click below button to copy the code. By JavaScript tutorial team

Solution 4:

In ECMAScript 6 we will actually be able to write exactly what we have:

function read_file(file, delete_after = false) {
  // Code
}
click below button to copy the code. By JavaScript tutorial team

This will set delete_after to false if it s not present or undefined. We can use ES6 features like this one today with transpilers such as Babel.

Solution 5:

that solution is work for me in js:

function read_file(file, delete_after) {
    delete_after = delete_after || false;
    // Code
}

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Set a default parameter value for a javascript function