JavaScript scope

var change8 = function() { console.log(a); console.log("End of function"); a = 10; } change8(); 

Link Return Error

 var change8 = function() { console.log(a); console.log("End of function"); var a = 10; } change8(); 

Return Undefined

Why does the first code return an Error link, but the second code returns undefined?

+6
source share
4 answers
 var change8 = function() { console.log(a); console.log("End of function"); a = 10; } change8(); 

variable a assigned undefined in the global context, because JavaScript is only hoist declarations, not initialization . Consider the same code as

 var a; // is = undefined // in global context var change8 = function() { console.log(a); console.log("End of function"); a = 10; } change8(); 

Therefore, you will get - Uncaught ReferenceError: a not defined

This will not happen in the second code because you explicitly declared your variable with var . Read more about the climb here .

+5
source

Javascript does something called hoisting, in which, before executing it, it searches for var declarations and creates these variables. Since you used var a in the second, it creates a variable, but when it is used, it is not defined. In the first case, a does not exist until you create it, so this is a link error.

+4
source

It is called variable hoisting . In JS, declared variables actually rise (move up) to the area to which they are attached, so in your case they move before the start of your function. In the second example, a processed as it is actually declared at the beginning of the method before any of the assignments, and then is assigned 10 later. Therefore, when you type a , the variable is defined, but its value has not yet been assigned.

 var change8 = function() { var a; console.log(a); console.log("End of function"); a = 10; } 

But in the first example, a is not defined with the var keyword, so a will be considered as a global variable and will not be available until destination. Thus, when it is called before the appointment, an error will occur.

To understand variable declarations with the var keyword, check the following answer

+1
source

This is because in the first fragment you use 'a' before declaring it with var, so 'a' refers to the global scope, hence the reference error when you call your method, because 'a' will only to the global scope when the third line of 'a = 10' was executed

The second “a” is undefined because it is used before it was declared using var, although it is still in the function area when the function is called at run time, the first line console. log (a) 'does not know' a '

0
source

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