I am learning JavaScript global and local variables, but I am confused on this particular function.
var text = "top";
function print() {
return (text);
}
print();
// Returns 'top'
I understands why it returns top. var text
is a global variable. print()
function has access to it and returns text
, thus returning 'top'
.
var text = "top";
function print() {
return (text);
var text = "bottom";
}
print();
// Returns undefined
I have a basic knowledge of global and local variables (or so I thought). I know that the function print
has access to its own local plus global variables.
I don't understand why this returns undefined
. To my understanding, the line return text;
retrieves global variable text
, which it has access to (as shown on the first code block). After returning text = 'top'
, it also declares its own local variable with the same name but different value, 'bottom'
. The local variable bottom
, to my knowledge, ought to sit there because it wasn't called earlier.
Why didn't it show top
(or even shows bottom
), but instead shows undefined
?