2

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?

0

3 Answers 3

5

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

1 Comment

Oh wow, the object passing is nice, haven't thought of that. Thanks :)
1

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

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

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

Comments

1

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

1 Comment

This is a nice alternative. Thanks :)

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.