Table of Contents

Background

  • AKA “optional parameters” and “optional arguments”, but without arity checking, all trailing arguments are optional in a real sense
  • ES4 default parameters, gleaned from the normative grammar and the reference implementation
  • var foo = arg || defaultFoo idiom for a function taking an optional parameter arg motivates one or both of
    • ||=, or perhaps ??= (a more precise operator inspired by C#)
    • default parameter values (these may abate the need for ||=)

Goals

  • Allow trailing formal parameters to receive default values if no corresponding actual parameters are passed
  • The default values should be computed in the scope of the callee, thus enabling use of
    • any parameters to the left of the one being given its default value, and of
    • any lexical and free (global) variables in enclosing functions and the top level

Syntax

  • The ES5 FormalParameterList production changes from:
  FormalParameterList ::=
    Identifier
  | FormalParameterList , Identifier
  • to this pair of productions:
  FormalParameterList ::=
    FormalParameter
  | FormalParameterList , FormalParameter

  FormalParameter ::=
    Identifier
  | Identifier = AssignmentExpression
  • Added restriction not expressed by this grammar: only trailing formal parameters may have default values specified by = AssignmentExpression

Semantics

  • When binding actual to formal parameters (see ES5 10.6 steps under 3(d)), for each formal parameter P from left to right:
    • If no actual parameter was passed for P, and
    • = AssignmentExpression was given to supply P with a default value, then:
      • Evaluate that AssignmentExpression in the scope of the fresh activation (localEnv in ES5 10.4.3) for the current function
      • Assign the result of evaluating the AssignmentExpression to P

Issues

  • It’s easy enough to elaborate the grammar to require that only trailing formal parameters may be given default values. Worth doing?
  • Clearly ES5’s 10.6 steps under 3(d) could be adapted, but I’m both (a) lazy and (b) hopeful that we’ll switch from pseudocode to a testable spec

Brendan Eich 2009/05/05 06:06

 
harmony/parameter_default_values.txt · Last modified: 2009/07/29 23:55 by brendan
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki