0

This works:

    var http = require('http');

    var handler = function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World!');
    }


    http.createServer(handler).listen(8080);

But this doesn't

    var http = require('http');

    http.createServer(handler).listen(8080);

    var handler = function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World!');
    }

I don't understand why since it should with hoisting all the more I got no error.

user310291
  • 36,946
  • 82
  • 271
  • 487
  • Because you haven't defined handler yet? It only passes variables by reference when it's an object – lumio Oct 17 '17 at 12:26
  • @lumio hoisting normally allows to define var afterwards so my question. – user310291 Oct 17 '17 at 12:27
  • Hoisting only applies to function declarations and not function expressions: https://stackoverflow.com/q/336859/1169798 – Sirko Oct 17 '17 at 12:28
  • @Sirko isn't mine a function declaration with var ? – user310291 Oct 17 '17 at 12:30
  • @user310291 but the way you wrote it, is that you define your function after you pass it. That might be the problem here – lumio Oct 17 '17 at 12:31
  • @user310291 You're using a function expression and not a declaration here. Maybe also see https://stackoverflow.com/q/1013385/1169798 – Sirko Oct 17 '17 at 12:31
  • @sirko ok thanks . – user310291 Oct 17 '17 at 12:33
  • 1
    There is no function hoisting for a function expression `var handler = function() {}`, only with function definition `function handler() {}`. In your function expression, only the variable itself is hoisted, not the assignment to it. – jfriend00 Oct 17 '17 at 12:41

2 Answers2

12

That's not function hoisting, that's variable hoisting. It's equivalent to this:

var http = require('http');
var handler;

http.createServer(handler).listen(8080);

handler = function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}

Function hoisting works only for function declarations (the above is a function expression):

var http = require('http');

http.createServer(handler).listen(8080);

function handler(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function#Function_declaration_hoisting

robertklep
  • 198,204
  • 35
  • 394
  • 381
1
var http = require('http');

http.createServer(handler).listen(8080);

var handler = function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}

In this case the declared function does not yet exist.

Alisson
  • 11
  • 1