In JavaScript the statement var
declares a global variable?!
So why
function myFunction(){
let var1 = varG
console.log(var1)
}
function myOtherFunction(){
var varG = document.all
myFunction()
}
myOtherFunction()
This displays the following error:
Uncaught ReferenceError: varG is not defined
This also happens if myOtherFunction
is after myFunction
.
2
Answers
JavaScript has the concept of scopes. For this case, the
var varG
statement only declares avarG
variable in themyOtherFunction()
function scope. WhenmyFunction()
is called, it has its own scope, which does not "inherit" or otherwise know about the scope its called from, and thus, does not know aboutvarG
, hence the error.var does not simply mean that variable declared is global. if you want to declare a global variable with var.Do like this