0

I noticed that when declaring a variable inside a function then trying to access this variable's value from outside the function's scope, i got a RefereceError but if i called this function and then tried to access the same variable's value i can reference it, my question is why the language behaves that way?

ability to call outside of function's scope

what i thought would happen that i'd get a reference error in either ways

  • 3
    [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) – Ivar Feb 28 '23 at 08:59

1 Answers1

0

Variable "a" does not exists until you call the "foo" function. After that, you can access and get the value of variable "a" wherever you want because you declare it as a global variable. Thats why you can not get the value before calling "foo" function, but after that, yes.

As a recommendation, is better to declare the variable in local scope, so you can only use it in the function scope, using "var" or "let" (better option) before the variable declaration. If you do that, then "a" variable will be only accessible in the function, and then it does not exists anymore.

Alberto Camino
  • 329
  • 2
  • 11