JamesGecko


You won’t believe the shocking truth about CoffeeScript’s named params

2015-05-02

CoffeeScript has named parameters. You can read about how to use them at this lovely guide to writing readable CoffeeScript. Unfortunately, they’re slightly broken.

method = (arg1, {foo, bar, baz}) ->
  console.log baz

method('arg1', foo: 'foo', bar: 'bar',
  baz: 'baz')
undefined

Wait, what? Why does method print undefined?

If you use named parameters, and you split them across a newline and indent, everything after the newline won’t be captured in the named params! It’s translated like this:

method('arg1', {
  foo: 'foo',
  bar: 'bar'
}, {
  baz: 'baz'
});

If you don’t indent, the second line, everything is fine!

method('arg1', foo: 'foo', bar: 'bar',
baz: 'baz')

becomes

method('arg1', {
  foo: 'foo',
  bar: 'bar'
  baz: 'baz'
});

You can make the failure explicit by wrapping it with curly braces

method('arg1', {foo: 'foo', bar: 'bar',
  baz: 'baz'})
Error on line 21: unexpected :

Whitespace is significant in CoffeeScript, but past me thought that those explicit parens in the method call would be enough to prevent nasty surprises. The error is insuduious enough that I’m unsure if I’ll keep using named params in CoffeeScript at all! Named params are most useful when writing functions that take a number of arguments. But a function that takes a lot of arguments is very likely to have them spill over to the next line, especially if you’re enforcing a maximum line length. At minimum, I’ll no longer be using them without curly braces.

© 2021 JamesGecko