title: Node JS anonymous functions and callbacks
body: <p>Someone please help me. I have been reading a lot of javascript documentation and fiddling with javascript.</p>
  
  <p>I am able to use the functions but I don't quite get this essential syntactic jazz going on here</p>
  
  <pre><code>          var http = require('http');
            http.createServer(function (req, res) {
                   res.writeHead(200, {'Content-Type': 'text/plain'});
                   res.end('Hello World\n');
            }).listen(1337, 'myhost');
  
            console.log('Server running at http://myhost:1337/');
  </code></pre>
  
  <p>I cant figure out why its okay to use req and res in the anonymous function above.  It's like they live somewhere inside of http. They are not declared anywhere! They are made up variable names in an anonymous function that reference inner objects or something. It's crazy.</p>
  
  <p>How does a callback function like this?</p>
  
  <p>or like </p>
  
  <pre><code>          stream.on('data', function(data){  
                  //  use data... i dont know where its coming from 
                  //  or how it got there, but use it
            });
  </code></pre>
  
  <p>If you could post a small example that mimics this process and syntax or explain how these callback functions can work like this or how I can pass these undeclared variables into functions like this I would greatly appreciate it.</p>
  
  <p>A similar example to the answer posted below. </p>
  
  <pre><code>     var b = {                  
             somefunction : function( data ){
                   var x = 100;
                   x = x+1;        // 101
  
                   return data(x); // returns the callback function data w/ value x
             } 
       };
  
       b.somefunction(function(foo){
             foo++;                // 101 + 1
             console.log(foo);     // prints 102
       });
  </code></pre>