Clarification on function default param values

Andreas Rossberg rossberg at google.com
Tue Oct 1 04:23:38 PDT 2013


On 30 September 2013 22:17, Jeff Morrison <lbljeffmo at gmail.com> wrote:
> So I think during the last meeting it was decided that we'd now have two
> scopes for functions with default param values: One for head/params, and one
> for the function body.
> Was it also agreed that we'd use let-binding (vs var-binding) for the
> default-value expressions?

I'm not entirely sure, actually. We discussed some pretty obscene
examples that would arise form doing a var-like thing, while nobody
came up with an example where it would be useful. I think in the end
the tendency was towards let-like, although I don't remember a formal
consensus. I assume let-like in my replies below.

> I also just wanted to clarify some of the awkward edge-case scenarios as I
> understand them to be sure we're all on the same page:
>
> var x=1, y=2;
> function foo(x=3, y=y, z=y) {
>   return [x, y, z];
> }

All parameters are in scope in the default expressions, so y is never
going to resolve to the global var binding. Also, all defaults are
being evaluated and bound left to right.

For more examples, see also my slides, which weren't yet linked in the
meeting notes that Rick posted:

https://github.com/rwaldron/tc39-notes/blob/master/es6/2013-09/default-arguments.pdf


> foo(); // [3, undefined, undefined] ? or [3, 2, 2] ?
> foo(2); // [2, undefined, undefined];

These two would throw, because y is used before being bound (just like
'let y=y' throws).

> foo(2, 3); // [2, undefined, undefined];

This one would be  [2, 3, 3].

> x; // 1
> y; // 2
>
>
> var x = 1, y=2;
> function foo(x=3,y=x+1) {
>   return [x, y];
> }
> foo(); // [3, 4];
> foo(2); // [2, 4];

No, [2, 3] for the latter.

> foo(2, 3); // [2, 3];
> x; // 1
> y; // 2
>
>
> var x = 1, y=2;
> function foo(x=3, y=(x=undefined,4)) {
>   return [x,y];
> }

This one I really dislike. I had actually proposed to disallow
assignment to other parameters in default expressions, but that got a
lot of resistance.

> foo(); // [undefined, 4]
> foo(2); // [undefined, 4]

Yes.

> foo(2, 3); // [2, 3] ? or [undefined, 3] ?

[2, 3], the default expressions are not evaluated if the argument
isn't undefined.

> x; // 1
> y; // 2
>
>
> function foo(bar=(function() { return 'param-inner'; })) {
>   var ret = bar();
>   function bar() {
>     return 'body-inner';
>   }
>   return ret;
> }
> foo(); // 'body-inner'
> foo(function() { return 'futility'; }); // 'body-inner'

Yes.

/Andreas


More information about the es-discuss mailing list