0

Just want to clear up some confusion regarding functions in JavaScript. Does a declared function create a variable with the function name in the same function scope and assign the function object to itself?

By code,

function name(){}

does it translate to,

var name = function name(){}

just before execution? If function is an object it should be held some where inside the scope by reference right?

Lakmal Caldera
  • 911
  • 1
  • 11
  • 23
  • Short answer: yes. Long answer: it does that, plus the function definition is hoisted along with the variable declaration to the top of the current scope. – Alexis King Dec 16 '14 at 04:25
  • @AlexisKing—there is no "hoisting". Variable and function declarations are processed before the code within a program is executed. – RobG Dec 16 '14 at 04:29
  • @RobG [I disagree.](http://stackoverflow.com/questions/15311158/javascript-hoisting) – Alexis King Dec 16 '14 at 04:30
  • [Check this SO questio](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) it has no direct answer but helps understanding the difference between 2 approaches – Gouda Dec 16 '14 at 04:30
  • @RobG - which is, conceptually, the same as "hoisting". Same result. (But of course you're right that the declarations aren't literally _moved_ to the top.) – nnnnnn Dec 16 '14 at 04:30
  • @nnnnnn—"hoisting" infers that the code is moved to the top, it isn't. The "hoisting" of function declarations is different to that of variable declarations: function declarations are effectively initialised when processed, before any code is executed. In contrast, for variable declarations including an initialiser, the declaration is processed before execution but the initialiser isn't executed until execution reaches it. – RobG Dec 16 '14 at 04:33
  • @RobG - I've always read (and used) the term "hoisting" in a metaphorical sense: as I said in my previous comment, I know the declarations are not literally moved. It is good to note the difference in how function and variable declarations are processed, thanks for spelling that out for the OP. – nnnnnn Dec 16 '14 at 04:36
  • Guys thnx for all your responses. – Lakmal Caldera Dec 16 '14 at 04:42
  • they very may well be hoisted to the top, just like in coffeescript, but we can't see under the hood. – dandavis Dec 16 '14 at 05:27

1 Answers1

0

Essentially yes with one exception.

In both your examples, the name function will be assigned to the name variable. In your first example the name variable and function definition will be hoisted to the upper most part of the current scope.

In your second example the name variable will be hoisted to the upper most part of the current scope but the definition will remain at it's current position in code.

Calummm
  • 546
  • 4
  • 13