Why can’t I access global variables inside my function in Javascript ?

Krishna Regmi
2 min readApr 5, 2019

--

When you declare global variable in javascript, you can access it from inside a function like so:

However, if you create a variable inside the scope of the function with the same name as a globalVariable, you lose access to the value of globalVariable inside the scope of the function.

If you read the code above by the order of which line gets executed, this is what you’d think would happen:

  • create globalVariable and assign it a value.
  • Call someFunction.
  • log value of globalVariable to the console. You’d expect this to log I am a globalvariable
  • create a new local variable with the same name as globalVariable. globalVariable and give it a value.
  • Log this new local variable. You’d expect I am a local variable as the same name as globalVariable to be printed.

However, you actually get an error. Javascript will tell you that globalVariable is not defined ReferenceError:globalVariable is not defined

Explanation:

This is because regardless of where you define your variable, it will hoist the variable to the top of their enclosing scope. Which means, if a variable is defined in a scope, javascript moves it all the way at the top of the scope. This is the same reason you can call a function in javascript on line 1 even though the function doesn’t get defined until line 2.

As a result in second example, you lose access to the globalVariable defined outside the scope of the function, because it has been hoisted to the top of the scope (aka inside the function).

--

--

Krishna Regmi

A tech-savvy creator type — leading change through data-driven decisions, and customer-first mentality.