3

I'm trying to understand why this code behaves the way it does:

test.js

var User;

console.dir(User);

function User(name) { // User = function(name) { ... seems not to be the same?
    this.name = name;
}

node test.js

[Function: User]

Why does User have a value before the function() statement?

conradkleinespel
  • 6,560
  • 10
  • 51
  • 87
  • 2
    possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Barmar Sep 21 '13 at 00:34
  • Function declaration statements are treated as if they appear at the very top of the function body, regardless of where they appear in the code. – Pointy Sep 21 '13 at 00:34
  • Named function definitions are treated differently from function expressions; similarly to `var` statements, they don't take effect at the point they appear in the source code. I'm not sure of the details, and I don't have a standard quote handy, so this is a comment. – user2357112 Sep 21 '13 at 00:35

2 Answers2

5

Hoisting! http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

var and function statements are automatically hoisted to the top of the script!

This allows functions to be used before they are defined, like this:

dothis();
function dothis() { alert('wow'); }

edit function statements like this are not affected:

myfunc(); // won't work
var myfunc = function() { alert('nope'); }
000
  • 26,951
  • 10
  • 71
  • 101
2

That function is defined at parse time.

Please refer to: var functionName = function() {} vs function functionName() {}

Community
  • 1
  • 1
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445