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
source share