Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mixing functions arguments that contain default values and no defaults doesn't work. #24

Open
davej opened this issue Jul 17, 2015 · 2 comments

Comments

@davej
Copy link

davej commented Jul 17, 2015

For example this works fine:

test-func = (foo = "foo", bar = "bar") ->
   return "hello world"

test-func()

But this breaks (with a match error):

test-func = (foo = "foo", bar) ->
   return "hello world"

test-func()

Would also be quite nice if these examples compiled to ES6 default arguments.

@MadcapJake
Copy link

Interestingly, it works if you call the function like test-func:.

It also works if you declare the parameters like this:

test-func2 = (foo or foo is "foo", bar) ->
   return "hello world"

print test-func2()

👍 on compiling to ES6 default args.

@breuleux
Copy link
Owner

This:

test-func = (foo = "foo", bar) -> 
   {foo, bar}

Is actually very different from setting a default value to bar. It is not supposed to work like it does in ES6. The syntax means that if only one argument is provided, then that argument is bar, and the default argument for foo is inserted at the beginning of the list of arguments. In other words:

test-func(1) == {"foo", 1}
test-func(1, 2) == {1, 2}

So basically the use case for the syntax is when your optional argument is the first one, for example:

subtract(a = 0, b) = a - b
subtract(1, 2) == 1 - 2 == -1
subtract(2) == 0 - 2 == -2

It might be a bit more consistent if bar was filled to undefined if no arguments are given at all, as is the case normally, but I think implicit defaults are kind of a wart of JavaScript to begin with, so I'm somewhat ambivalent about "fixing" that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants