0

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.

Wongjn
  • 8,544
  • 2
  • 8
  • 24
  • `var` doesn't make them global, it makes them hoisted (declared from the top of the nearest function scope). So in your example `varG` only exists in that one function, `myOtherFunction`. Declaring with `var` is only global when declaring them in global space (eg not inside a function). – Patrick Evans Apr 28 '23 at 12:30

2 Answers2

1

JavaScript has the concept of scopes. For this case, the var varG statement only declares a varG variable in the myOtherFunction() function scope. When myFunction() 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 about varG, hence the error.

Wongjn
  • 8,544
  • 2
  • 8
  • 24
0

var does not simply mean that variable declared is global. if you want to declare a global variable with var.Do like this

var varG;
function myFunction(){
  let var1 = varG
  console.log(var1)
}
function myOtherFunction(){
   varG = document.all
  myFunction()
}
myOtherFunction()
MenTalist
  • 84
  • 8
  • ok thank you very much I understood my mistake, in fact the variables defined with var do not have a global scope but the function as a scope – Manthe fraiche Apr 28 '23 at 13:03