0

Why does function expressions does not be in stack if it is invoked before its occurence?

console.log( myFunc());
var myFunc = function(){
};

Regular function declaration works right.

user2111006
  • 375
  • 1
  • 2
  • 6
  • `var myFunc;console.log(myFunc());myFunc=function(){}` – elclanrs Oct 25 '14 at 17:42
  • possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) –  Oct 25 '14 at 18:18
  • Ask and answered dozens of times here on SO. Please search for "function hoisting". –  Oct 25 '14 at 18:18

1 Answers1

-1

This confusion is due to one major difference in the way that a JavaScript engine loads data into the execution context. Function declarations are read and available in an execution context before any code is executed, whereas function expressions are not complete until the execution reaches that line of code.

console.log(myFunc());
function myFunc(){
 //
}

This works because of function declaration hoisting.

Without function declaration hoisting, the top of the source tree, will be empty. Hence you get the unexpected identifier error for your code.

InfinitePrime
  • 1,400
  • 12
  • 16
  • To be more precise, this has nothing to do with function expressions. Given a variable declaration with initialization, only the declaration is hoisted, not the initialization itself. This only happens when the line of the assignment is reached. – Felix Kling Oct 25 '14 at 18:19
  • @FelixKling OP has asked, why the function that is a part of the initialization statement and not a part of function declaration is causing an error. I have given the accurate reason as to why. I really don't appreciate your unnecessary down vote. – InfinitePrime Oct 26 '14 at 08:06
  • You shouldn't jump to conclusions and think that I downvoted just because I commented. – Felix Kling Oct 26 '14 at 08:14
  • I did think you did that. Sorry for that. – InfinitePrime Oct 26 '14 at 08:24