TIMEX
TIMEX

Reputation: 272164

How do I pass in argument names when I call a function?

function go(a, b){
        console.log(a);
        console.log(b);
    }

go(b="happy", a="sad");

How can I make this work, just like it does in python?

Upvotes: 0

Views: 58

Answers (3)

cwallenpoole
cwallenpoole

Reputation: 82058

While there are some libraries which claim that they will let you do that (Prototype has a backwards way of making this possible), it is not cross browser compliant and it certainly isn't the the ECMAScript specification that JS is based off of.

The only way to have reliable behavior is to use the arguments in the order they were listed.

Upvotes: 0

John
John

Reputation: 360

go(sad, happy);

Just be sure you use the same order. If the function is declared as:

function(a,b){}

Then the attributes must be a,b; not b,a.

Alternatively, if you really want to name them, use a colon in front of the attribute name.

Upvotes: 0

Mikola
Mikola

Reputation: 9326

Not really part of the language, but you can fake it like this: http://www.javascriptkit.com/javatutors/namedfunction.shtml

Example:

function go( params ) {
    console.log(params.a);
    console.log(params.b);
}

go( { b:"happy", a:"sad"} );

Upvotes: 3

Related Questions