Prince Merluza
Prince Merluza

Reputation: 133

Choose what arguments to pass for function. Javascript

In other languages, when calling functions you could choose what parameters to pass with.

So for example

int cookMeth(x=0,y=0,z=0){...}

cookMeth(z=123);

My question is, is it possible for js? It doesn't seem to be but what are the alternatives or techniques for doing this?

Upvotes: 2

Views: 64

Answers (3)

tenbits
tenbits

Reputation: 8018

Quentin has already replied to your question, I want just to add, that sometimes, you could rely on arguments types, and in that way to distinguish them, but there are more work to do:

function some(){

    var name,
        birth;

    if (typeof arguments[0] === 'string') {
        name = arguments[0];
        birth = arguments[1] || new Date();
    } else{
        name = 'Anonym';
        birth = arguments[0];
    }

    // ...
}


some('foo', new Date(1500, 1, 1));
some(new Date(1500, 1, 1));

Upvotes: 1

Steve
Steve

Reputation: 50583

What you could do is use an object in the following way:

Method({ param : 1, otherParam : "data"});

function Method(options){
    var variable = options.param;
}

Upvotes: 1

Quentin
Quentin

Reputation: 944559

No, it isn't.

All arguments are optional, but you can't skip arguments.

You can:

Explicitly pass values to be ignored

exampleFunction(undefined, undefined, 123);

Pass an object instead

function exampleFunction(args) {
    var x = args.x, y = args.y, z = args.z;
}

exampleFunction({ z: 123 });

Upvotes: 6

Related Questions