jashkenas / coffeescript

Unfancy JavaScript
https://coffeescript.org/
MIT License
16.51k stars 1.99k forks source link

Default argument values #802

Closed TrevorBurnham closed 14 years ago

TrevorBurnham commented 14 years ago

If I'm not mistaken, there hasn't been a substantive discussion of default argument values since issue 49 was closed all the way back in January. There's been enough interest that the issue has been raised at least twice since, and there's been at least one implementation. I think now is a good time to raise the issue afresh, as the language verges on 1.0. Also, the discussion of issue 788, which would provide a keyword for self-executing closures, has hit a stumbling block due to the lack of syntax for providing arguments to functions while defining them.

The main argument against default argument values has been that they clutter function definitions, and that providing "default" values within functions is easy:

(foo) ->
  foo ?= bar

Those arguing in favor have emphasized the succinctness of placing the defaults in the function definition, and pointed out that this feature is offered by Ruby, Python, and many other fine languages.

Now there's an additional reason to add default argument values: to provide a syntax for passing values to self-executing closures using the do keyword. (Again, see issue 788.) Just as support for YAML-style object construction was sufficient reason to drop the : assignment syntax, perhaps support for do-style closures is sufficient reason to add a default argument syntax.

Personally, I favor the Ruby/Python/Groovy/PHP/Scala-esque syntax

(foo = bar) ->
  # do things with foo...

as equivalent to

(foo) ->
  foo ?= bar
  # do things with foo...

Thoughts?

jashkenas commented 14 years ago

Alrighty -- default arguments is now merged to master. Syntax highlighting needs to come next ;) ...

It uses a slightly modified version of satyr's branch.

func = (options = {}) ->

Compiles into:

func = function(options) {
  options != null || (options = {});
};

Which is actually slightly faster than an if or a ternary in Chrome and Firefox:

http://jsperf.com/default-args-or-vs-if/2

Closing the ticket -- thanks, satyr.