How can you use a function that is defined below its use?

I always thought that function a(){} is identical to a = function(){};

However, these two fragments behave differently:

 a(); function a() { alert("Booya"); } 

Seal of Booya.

 a(); a = function() { alert("Booya"); } 

It does not work with an exception, which makes sense, since a is really not defined when called.

So - what "magic" allows you to work with the first fragment, although a() is defined below its point of use?

+6
source share
5 answers

This is the difference between a function declaration and a function expression. This difference is well described, for example, here .

+6
source

See this article for an explanation: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Function declarations and variable declarations always move ("rise") invisibly to the top of their area using a JavaScript interpreter.

+2
source

In JavaScript, all ads go up. This means that a variable can be used before it is declared, and a function can be used before it is declared . Its default behavior is for JavaScripts to move all ads at the top of the current script.

But this function can lead to errors in the application, so we use the strict mode directive to avoid errors. Strict mode does not allow the use of variables without declaration.

more info on here

+1
source

No magic, proper coding required. AFAIK

  • Document
  • loaded and analyzed, functions loaded. The script is being executed. No issues found _a () _ yet.
  • no function is displayed. The script si line is executed. It tries to call function () and THEN for global variable a
0
source

Functions are defined global. But if you assign a function to a variable, as in the second case, the scope rules for variables come into effect: you cannot call a function before its variable has been defined.

-1
source

Source: https://habr.com/ru/post/898657/


All Articles