This question has already been answered:

In the next experiment, we have one "outer" function outerFunction() and two inner functions, as well as two variables. The first of them is declared at the beginning of the external function, the second is also in the external, but between internal functions.

 function outerFunction(){ var testVar1 = 'test1'; innerFunction1(); innerFunction2(); function innerFunction1(){ console.log('InnerFunction1() has been executed') } var testVar2 = 'test2'; function innerFunction2(){ console.log('testVar1: '+testVar1); console.log('testVar2: '+testVar2); } } outerFunction(); 

If we look at the console, we see that testvar2 is of type undefined . The same will happen if you declare this variable at the end of an external function.

I correctly understood that variables initialized at the beginning of an external function are first initialized, then internal functions? The declaration of the textVar2 variable is textVar2 stylistically correct, but still: when will it be initialized?

Reported as a duplicate at Grundy. javascript Apr 10 '17 at 9:45 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    In JavaScript, all variables are raised to the beginning of a function. This process is called Hoisting . It does not matter where you describe the variable in the function - it will rise to the beginning of the function, but the value will be assigned to it in the place where you set the = operator.

    Your code is equivalent to the following:

     function outerFunction(){ var testVar1; var testVar2; testVar1 = 'test1'; innerFunction1(); innerFunction2(); function innerFunction1(){ console.log('InnerFunction1() has been executed') } // до этого момента testVar2 равен undefined testVar2 = 'test2'; function innerFunction2(){ console.log('testVar1: '+testVar1); console.log('testVar2: '+testVar2); } } outerFunction(); 

    Therefore, it is recommended to declare and initialize all variables at the beginning of the function. It is also worth remembering that the scope of var limited to function.

    • Functions declared in this way also pop up, so they will work even if they are put in return - vp_arth