Today, I got completely surprised when I saw that a global variable has undefined
value in certain case.
Example:
var value = 10;
functi
Variables in JavaScript always have function-wide scope. Even if they were defined in the middle of the function, they are visible before. Similar phenomena may be observed with function hoisting.
That being said, the first console.log(value)
sees the value
variable (the inner one which shadows the outer value
), but it has not yet been initialized. You can think of it as if all variable declarations were implicitly moved to the beginning of the function (not inner-most code block), while the definitions are left on the same place.