I am studying JS global and local variables, but I am confused about this particular function.
var text = "top"; function print() { return (text); } print();
I understand why he returns to the top. var text is a global variable. print() has access to it and returns text , thereby returning 'top' .
var text = "top"; function print() { return (text); var text = "bottom"; } print();
I have a basic knowledge of global and local variables (or so I thought). I know that the print function has access to its local plus global variables.
I do not understand why this returns undefined . As I understand it, the string return text; retrieves the global variable text , to which it has access (as shown in the first block of code). After returning text = 'top' it also declares its own local variable with the same name but with a different value of 'bottom' . The local variable bottom , as far as I know, should sit there, because it was not called before.
Why didn't he show top (or even show bottom ), but instead show undefined ?
source share