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

user1692342
  • 5,007
  • 11
  • 69
  • 128

4 Answers4

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); 
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
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); 
suvroc
  • 3,058
  • 1
  • 15
  • 29
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'});
Luke
  • 5,567
  • 4
  • 37
  • 66
0

You can use either of the below two syntax:

helo(null,parameterB); 

or

helo(undefined,parameterB); 
Tarang
  • 318
  • 1
  • 10