skip to Main Content

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


  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.

    Login or Signup to reply.
  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search