Is there a better way to do optional function parameters in JavaScript?

This question already has an answer here:

  • Set a default parameter value for a JavaScript function 13 answers

  • Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative

    if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }
    

    Or an alternative idiom:

    optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;
    

    Use whichever idiom communicates the intent best to you!


    I find this to be the simplest, most readable way:

    if (typeof myVariable === 'undefined') { myVariable = 'default'; }
    //use myVariable here
    

    Paul Dixon's answer (in my humble opinion) is less readable than this, but it comes down to preference.

    insin's answer is much more advanced, but much more useful for big functions!

    EDIT 11/17/2013 9:33pm: I've created a package for Node.js that makes it easier to "overload" functions (methods) called parametric.


    In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration:

    function myFunc(requiredArg, optionalArg = 'defaultValue') {
        // do stuff
    }
    

    More about them in this article on MDN (despite the article title, they're called "arguments," not "parameters," in JavaScript).

    This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly.

    链接地址: http://www.djcxy.com/p/348.html

    上一篇: 方法和函数之间的区别

    下一篇: 有没有更好的方法来在JavaScript中做可选的函数参数?