What are the situations where a function can't access global variables? And why?

Viewed 932

I just run into this situation:

var testing = 'thing 1';

function func() {
  console.log(testing);

  var testing = 'thing 2';

  console.log(testing);
}

func();

I expected the above code to log 'thing 1' and only then 'thing 2'. However, 'thing 1' is never logged.

At first I thought it could be some behavior of static functions to reserve the testing variable to its scope, thus it being undefined instead of 'thing 1'.

However, thinking more about it I'm not sure anymore if it is really a static function neither if my own explanation (which looked correct initially) is valid.

Why testing variable is undefined inside func? Why can't func access global variables? Are there any other situations like this?

PS: I tried to find a dupe, but failed.

2 Answers
Related