tldr
tldr

Reputation: 12112

coffeescript : defining callbacks before they're called

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?

Upvotes: 0

Views: 132

Answers (1)

zdyn
zdyn

Reputation: 2173

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.

Upvotes: 2

Related Questions