Search code examples
javascriptfunction-parameter

Javascript: Only using specific parameter in function


I think it is rather a beginner's question: How can I address a specific parameter in a function and ignore the others?

Example:

http://jsfiddle.net/8QuWj/

function test(para_1, para_2, para_3) {
   if (para_3 == true) {
    alert('only the third parameter was successfully set!');
   }
}

test(para_3=true);

I want to individually decide whether or not I use a certain parameter in a function or not.


Solution

  • You can check each parameter separately using an if(param), like:

    function test(para_1, para_2, para_3) {
        if (para_1) {
            // First parameter set
        }
        if (para_2) {
            // Second parameter set
        }
        if (para_3) {
            // Third parameter set
        }
    }
    

    Generally speaking, you cannot set only one parameter and expect it to be the third, because it will automatically set it to the first one, and the remaining 2 as undefined. So if you would like to call your function and only have the third set, most probably you'd do a

    test(null, null, 'this_is_set');