title: JavaScript callback vs return
body: <p>I have a JavaScript (Node) function to grab the content of a web page and handle it with a callback:</p>
  
  <pre><code>'using strict';
  var http = require('http');
  
  function download(url, callback) {
    http.get(url, function(res) {
      var content = '';
      res.on('data', function (chunk) {
        content += chunk;
      });
      res.on('end', function() {
        callback(content);
      });
    }).on('error', function() {
      callback(null);
    });
  }
  </code></pre>
  
  <p>What I don't understand is why I can't simply return the result on 'end'. Clearly, when the 'end' event is emitted, the 'content' variable contains a string with the content of a web page, otherwise it couldn't be submitted to the callback function, so why can't I just return it like this:</p>
  
  <pre><code>function download2(url) {
    http.get(url, function(res) {
      var content = '';
      res.on('data', function(chunk) {
        content += chunk;
      });
      res.on('end', function() {
        return content;
      });
    }).on('error', function() {
      return null;
    });
  }
  </code></pre>
  
  <p>download2 always returns undefined. Why?</p>