jashkenas--coffeescript/documentation/sections/unsupported_named_functions.md

1.6 KiB
Raw Blame History

Named functions and function declarations

Newcomers to CoffeeScript often wonder how to generate the JavaScript function foo() {}, as opposed to the foo = function() {} that CoffeeScript produces. The first form is a function declaration, and the second is a function expression. As stated above, in CoffeeScript everything is an expression, so naturally we favor the expression form. Supporting only one variant helps avoid confusing bugs that can arise from the subtle differences between the two forms.

Technically, foo = function() {} is creating an anonymous function that gets assigned to a variable named foo. Some very early versions of CoffeeScript named this function, e.g. foo = function foo() {}, but this was dropped because of compatibility issues with Internet Explorer. For a while this annoyed people, as these functions would be unnamed in stack traces; but modern JavaScript runtimes infer the names of such anonymous functions from the names of the variables to which theyre assigned. Given that this is the case, and given that not all functions in function expressions can be named (for example, the functions in first.fn = ->; second.fn = -> cant both be named fn) its simplest to just preserve the current behavior.