In this code “a” is defined as a global variable and should be accessible to all the functions.So quite naturally the function “f” will print “global” i.e. value of the global variable “a” in the console.
In the code below, we have introduced a small change and added declaration of another variable named “a” in the function “f”.
Here the program will give precedence to the local variable “a” and will print “local” to the console. So far it’s quite intuitive.
Here we are trying to access the value of “a” first followed by the local variable declaration of same name and then again printing it’s value to the console. Most of us would expect to the following in the console.
It will print the following instead:
So this can lead to undesirable behavior and it is safe to declare the variable at the top of the function before its use.