Is it possible to name a parameter when the function is called?

8

Can I "access" a specific parameter of a JavasScript function, ie give a value for a given parameter? As an example is better than text (since I can not explain myself right), here's one:

In Python, having a function:

def funcX(A="A",B="B",C="C"):
    print(A+B+C)

... that would result in:

'ABC'

... I can change the value of a certain parameter like this:

funcX(C = "c")

... which results in:

'ABc'

I want to know if there is any way to do the same in JavaScript. Example:

function funcX(A,B,C){        
    if(typeof A != 'string'){A= "A"}
    if(typeof B != 'string'){B= "B"}
    if(typeof C != 'string'){C= "C"}

    alert(A+B+C)
};

It would result in:

'ABC'

And then I would like to do something like:

funcX(C = "c")

... to result in:

'ABc'

Taking advantage of this, I'd like to ask a parallel question (if that's allowed): Is there a better way to give "default values" for JavaScript function parameters than if(typeof A != 'string'){A= "A"} ?

As in Python def funcX(A="A")

* (sorry for the comparison, but I learned to program in Python, and that's the only reference I have)

    
asked by anonymous 28.01.2015 / 15:36

2 answers

6

In JavaScript you have to call the function by passing all parameters. The function you put is well on the right path, if you have:

function funcX(A,B,C){        
    if(typeof A != 'string'){A= "A"}
    if(typeof B != 'string'){B= "B"}
    if(typeof C != 'string'){C= "C"}

    alert(A+B+C)
};

So if you just want to change the C would call the function with funcX(null, null, 'c'); .

jsFiddle: link

Another way to give default values would be:

function funcX(A,B,C){        
    A = A || 'A';
    B = B || 'B';
    C = C || 'C';

    alert(A+B+C)
};

jsFiddle: link

But I think how you have is better, more specific. In case you do not need to redefine any parameters you can call the function with only funcX();

jsFiddle: link

    
28.01.2015 / 15:48
4

The usual way to make named or optional Javascript parameters is to pass an object (dictionary) as a parameter. A famous example is the jQuery ajax function.

In your case it would look something like this:

function funcX(kw){
    var A = kw.A || "A";
    var B = kw.B || "B";
    var C = kw.C || "C";
    console.log(A+B+C);
}

funcX({a:"oi", c:"!", b:"mundo"});

It is very common to use || in optional parameters in JS because the code is very succinct but if you want to accept false values like 0 or "" you can do more accurate tests using typeof or the in :

 var A = "A" in kw ? kw.A : "defaultA";
    
28.01.2015 / 17:02