I have a function which looks like this:
function helo(a,b){
if(a)
{
//do something
}
if(b)
{
//do something
}
}
Now if I want to specify which parameter has to be passed while calling helo, how do I do it in javascript, i.e
If I want to send only parameter b, how do I call the function helo?
helo(parameterB);
Right now parameter a takes the value
I have a function which looks like this:
function helo(a,b){
if(a)
{
//do something
}
if(b)
{
//do something
}
}
Now if I want to specify which parameter has to be passed while calling helo, how do I do it in javascript, i.e
If I want to send only parameter b, how do I call the function helo?
helo(parameterB);
Right now parameter a takes the value
Share Improve this question asked Jul 2, 2015 at 14:32 user1692342user1692342 5,24713 gold badges79 silver badges138 bronze badges 1- That should work. However what I am looking for is if there is a way to specify the exact parameter – user1692342 Commented Jul 2, 2015 at 14:35
4 Answers
Reset to default 9Your best bet would be to just pass an object containing all parameters:
function myFunction(parameters){
if(parameters.a) {
//do something
}
if(parameters.b) {
//do something
}
}
Then you can call the function like this:
myFunction({b: someValue}); // Nah, I don't want to pass `a`, only `b`.
In case you want to be able to pass falsy
values as parameters, you're going have to change the if
s a bit:
if(parameters && parameters.hasOwnProperty('a')){
//do something
}
Another option would be to simply pass null
(or any other falsy
value) for parameters you don't want to use:
helo(null, parameterB);
In JavaScript parameters is matched according to order, so if you want to pass only second parameter, you must leave first one empty
helo(null,parameterB);
Instead of passing multiple distinct arguments, you can pass in a single argument, which is an object.
For Example:
function helo(args){
if(args.a){ ... }
if(args.b){ ... }
}
helo({b: 'value'});
You can use either of the below two syntax:
helo(null,parameterB);
or
helo(undefined,parameterB);