Local and global variables inside a JavaScript function
JavaScript hoists your variable declaration such that your code is functionally the following:
var text = "top";
function print() {
var text;
return (text);
// Unreachable code below
text = "bottom";
}
print();
// Returns undefined
Since text
, as declared in your function, is not yet defined when you hit return(text)
, and text="bottom"
is unreachable, print()
returns undefined
.
See What is the scope of variables in JavaScript? for more. This question relates to case 7.
This is to do with variable hoisting
The code in your second example is executed in this order:
- Declare global variable
text
- Set value of global variable
text
to "top" - Declare function
print
- Call function
print
- Declare local variable
text
(due to hoisting) - Return value of local variable
text
(undefined
at this point) - Set value of local variable
text
to "bottom"
It is executed as if it were written like this:
var text = "top";
function print() {
var text;
return (text);
text = "bottom";
}
print();
As you can see, the value of text
is returned before actually being defined, and therefore it is undefined
.