CoffeeScript and Named Functions

coffeescriptfunctions

Elsewhere, an argument has arisen over the terminology of a named function in CoffeeScript. In particular someone referred to something like this:

 foo = ->
    console.log("bar")

as a named function. But its been objected that everything in CoffeeScript is anonymous functions and there are no named functions. This is certainly true, CoffeeScript only has function expressions which can then be stored in a variable. But I don't think that means it is wrong to call this a named function.

As I see it, it is a named function because its a function that has been given a name. True, its not a named function in the same way that some other languages have named functions, but I think its close enough that it's not inappropriate to call it a named function. To insist otherwise just seems to be nitpicking.

Am I out to lunch in thinking that insisting that this isn't a named function is just nitpicking?

Best Answer

CoffeeScript is inexorably tied to JavaScript, and JavaScript differentiates between the following expressions:

function foo() { ... }
var foo = function () { ... }

In fact, you can even write:

var foo = function bar () { ... }

Since this difference matters in JavaScript, it makes sense to use the same terms when talking about CoffeeScript. However, CoffeeScript does not support anything like the function foo () syntax, so we can say it does not have "named" functions.

In a sense, the name is part of the function definition in the function foo() { ... }, where in the other case you just create a function and assign it to a variable. This is reflected, for example, in the (nonstandard) name property of functions: in the first case, foo.name will give you "foo" and in the second it will give you "".

Additionally, in JavaScript, these also differ in terms of how they get introduced to the scope: the first version is "hoisted" and available throughout its scope where the second definition is only available after it's assigned.

Basically, just think of it as JavaScript-specific jargon, which is transferred to CoffeeScript because CoffeeScript is so closely related to JS.

Related Topic