0

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){}
Westerfaq
  • 91
  • 1
  • 8
  • No, however you can use the length of `arguments` to decide how to use said arguments. – Kevin B Apr 28 '14 at 18:06
  • possible duplicate of [method overloading in Javascript](http://stackoverflow.com/questions/12694588/method-overloading-in-javascript) – Bergi Apr 28 '14 at 18:07
  • This would be a good opportunity for a small open-source library that implements var args. – Brandon Apr 28 '14 at 18:08

2 Answers2

1

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.

forgivenson
  • 4,394
  • 2
  • 19
  • 28
1

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)

    }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Great! Do i have to check with `===` or am i good with just `==`? – Westerfaq Apr 28 '14 at 18:32
  • `===` is a better overall javascript habit to get into (because it avoids implicit type conversions which you usually do not want), though either `===` or `==` will work here. – jfriend00 Apr 28 '14 at 18:38