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:

  1. Declare global variable text
  2. Set value of global variable text to "top"
  3. Declare function print
  4. Call function print
  5. Declare local variable text (due to hoisting)
  6. Return value of local variable text (undefined at this point)
  7. 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.