2

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

1
  • That should work. However what I am looking for is if there is a way to specify the exact parameter Commented Jul 2, 2015 at 14:35

4 Answers 4

9

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

Comments

2

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); 

Comments

1

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'});

Comments

0

You can use either of the below two syntax:

helo(null,parameterB); 

or

helo(undefined,parameterB); 

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.