0

I'm writing a basic node.js web server in coffeescript. When I write:

server.listen(3000, listener)
listener = () ->
  console.log 'server listening on port 3000'

It starts the server, but doesn't print the message. So I gather that the callback isn't being called. On the other hand, when I do:

listener = () ->
  console.log 'server listening on port 3000'
server.listen(3000, listener)

the message is printed on the console.

Why does the callback get called if it's defined before the call, but not if it's defined afterwards?

Jean-Bernard Pellerin
  • 12,062
  • 9
  • 54
  • 74
tldr
  • 10,743
  • 11
  • 69
  • 111
  • Related: http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname. CoffeeScript does not generate named functions (outside of classes). – zdyn Jun 22 '13 at 20:11

1 Answers1

2

Due to the way CoffeeScript function definitions work, your first snippet is equivalent to something like this in JavaScript:

var message;
console.log(message()); // message is undefined at this point
message = function() { return "Hello World!"; };

message doesn't exist when it is first accessed, so this throws an error. It sounds like you want:

console.log(message());
function message() { return "Hello World!"; }

Which works fine, but AFAIK, there is no way to write that in CoffeeScript.

zdyn
  • 2,053
  • 1
  • 14
  • 17
  • yep, i was about to link http://stackoverflow.com/a/16549446/1375688, but yeah you're right. – tldr Jun 22 '13 at 20:21
  • The `var listener` happens before the `server.listen` call and the `listener = function() { ... }` happens after. So `listener` does exist (or the JavaScript engine would give you a ReferenceError) but its value is `undefined` so they're actually doing `server.listen(3000, undefined)`. So you're on the right track but the details are a bit off. – mu is too short Jun 22 '13 at 20:27