Why can I access normal functions before the declaration, but the anonymous functions do not? [duplicate]

5

In Javascript, you can use / use a function before your declaration.

MyFunc();
function MyFunc() {
  return console.log('blah!');
}

However, when it comes to anonymous functions and closures, it is not possible to do the above example:

var MyFunc;

MyFunc();

MyFunc = function () {
  return console.log('Nada de Blah!');
};

Although I know it works that way, I never knew why.

Why does this happen?

    
asked by anonymous 05.12.2016 / 16:47

1 answer

3

As per I answered PHP the compilation is done in two steps. Unlike the normal function that is a statement, the anonymous function is part of the algorithm and is not analyzed in the first step, so it can not be considered in the first step, while parsing the statements. In the second step is already late, only the symbols generated in the first step will be considered, or what can be interpreted until that point of the code in the second step. But it has a complicator.

Because it is a dynamic language and the value of the variable can even cease to be a function, it can not guarantee that it will have the function there, the verification can only be done at the moment of its execution. It is a problem similar to the include reported in the PHP question.

If the language were typed MyVar you would have to function signature , then the question code would work, no matter where the "variable" was declared. Note that I'm speaking until the statement, nor does it have to be the definition .

    
05.12.2016 / 17:34