Default argument values

Steven Mascaro subs at voracity.org
Wed Feb 27 17:22:28 PST 2008


> Functions can take optional arguments (they have default values) and
> rest arguments:
>
>  function f(x, y=0) { ... }   // y is optional
>

What is the opinion on Python-style named arguments? i.e.:

def f(x = 0, y = 0):
	...

f(y = 2)

The calling syntax for ES4 would obviously have to be different (is a
':=' operator too incongruous in ES4?).

I find I rarely use unnamed optional arguments, because once you have
more than 1, they become very awkward to deal with. In the past, I
invariably found myself writing code like this (in PHP):

function f($a, $b = null, $c = null, $d = D_DEFAULT) {
	if ($b==null) { $b = B_DEFAULT; }
	if ($c==null) { $c = C_DEFAULT; }
}

I would then call the function this way:

f(A_VALUE, null, null, D_VALUE);

Which would get very confusing with a large number of optional arguments:

f(A_VALUE, null, null, null, null, null, null, VALUE);

Now instead I try to write functions that take a php array for
optional arguments:

function f($a, $opts = array(), $b = B_DEFAULT, $c = C_DEFAULT, $d =
D_DEFAULT) {
	extract($opts);
}

and call it like this:

f(A_VALUE, array("d" => D_VALUE));

The Python syntax is obviously far more elegant in both cases (and, I
assume, would be faster to run as it would have no extra runtime
overhead over positional arguments).

Besides syntactic simplicity and elegance, I also use named arguments
for 'self-documenting' code (both when arguments are mandatory and
optional). For example, I might write things like this in Python if I
feel I need to make things clear:

drawBox(x = 0, y = 0, width = 45, height = 70)
copy(source = fileA, dest = fileB)

Anyway, I'm sure you know the advantages (and disadvantages?) to
optional named arguments. I was just wondering whether they had been
considered for ES4, or if considered and rejected, then why. I've
searched the wiki and mailing list, but couldn't find anything. I also
remember some brief comments on it a short while ago, but can't find
them now.



More information about the Es4-discuss mailing list