3

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.

1
  • Pass a hash map to the function Commented Jul 6, 2014 at 13:02

3 Answers 3

3

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');
Sign up to request clarification or add additional context in comments.

Comments

2

It is not possible in JavaScript to pass named arguments. The best you can do is to accept an object as a single parameter, and from there, you decide which properties to set.

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

test({para_3:true});

4 Comments

This is incorrect; you can assert the parameter doesn't equals undefined.
@JimmyBreck-McKye what part is incorrect? I think this answer is the best fit to what OP is looking for.
@Segfault - The OP wants to determine if the parameter 'para3' was passed. Scimonster says this isn't possible, but it is - you can check if para3 === undefined. Whilst the map argument approach is more flexible and more readable for multiple optional parameters, it is not, as the answer suggests, the only option the language provides.
@JimmyBreck-McKye I changed my answer a little.
0

You can also apply Arguments stored in an array. The entrys of the argument array will be mapped to the paramters of the function.

var arg = [];
arg[2] = true;
test.apply(this, arg);

the other way is to just set the other params to undefined:

test(undefined, undefined, true);

http://jsfiddle.net/8QuWj/2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.