Westerfaq
Westerfaq

Reputation: 89

Variable number of arguments in a function

Is it possible to tell a function what names it should give to its arguments, based on the number of arguments passed? Like this:

function soSwag(swagLevel, swagStart, swagDuration || swagStart, swagStop){}

Upvotes: 0

Views: 54

Answers (2)

jfriend00
jfriend00

Reputation: 707288

What some popular libraries (e.g. jQuery) that support variable types of arguments do is that they examine the arguments and then swap values accordingly:

function soSwag(swagLevel, swagStart, swagDuration) {
    if (arguments.length === 2) {
        var swagStop = swagStart;   // 2nd arg becomes swagStop
        swagStart = swagLevel;      // first arg becomes swagStart

        // code here that uses swagStart and swagStop
        // as called like soSwag(swagStart, swagStop)

    } else {

        // code here that uses swagLevel, swagStart, swagDuration
        // as called like soSwag(swagLevel, swagStart, swagDuration)

    }
}

Upvotes: 1

forgivenson
forgivenson

Reputation: 4435

Not to my knowledge. However, you can just pass in an object with the data you want.

soSwag({
    swagStart: 10,
    swagStop: 100
});

However, it might be cleaner to simply pass null into that first parameter.

Upvotes: 1

Related Questions