Search code examples
javascriptfunctiondefault-parameters

correctly specify parameter values when calling a function in JavaScript


I have a function foo defined as follows,

foo = function(a=1,b=2,c=3){
    console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".")
}

How do I use the default value of b and specify a and c only when calling the function?

For example, I would like to return a console log of your inputs are a:3, b:2, c:1. when calling foo(a=3,c=1).

However, by calling foo(a=3,c=1), the console log is your inputs are a:3, b:1, c:3.. The JavaScript thinks the c=1 should be the value of the second parameter b and the third parameter c is not given and will use its default value of 3. In addition, by calling this function, the object of a and c are also created.


Solution

  • I'd pass an object instead, and destructure the arguments:

    function foo ({ a=1,b=2,c=3 }){
        console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".")
    }
    
    foo({ a: 99, c: 99 });

    In case the function may be called without any parameter, assign the default parameter to {} too:

    function foo ({ a=1,b=2,c=3 } = {}){
        console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".")
    }
    
    foo();

    You can also explicitly pass undefined for missing arguments:

    function foo (a=1,b=2,c=3){
        console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".")
    }
    
    foo(99, undefined, 99);