javascriptfunctionloggingscopeoutput

Why is the result of this JavaScript code "undefined"?


I am trying to figure out why the result of this Javascript code in the browser's console window is undefined? Shouldn't it be "outside"?

var text = 'outside';
function logIt(){
    console.log(text);
    var text = 'inside';
};
logIt();

Thanks


Solution

  • This is a result of "variable hoisting". (See http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.)

    To make the code behave as you expect, you need to either assign the variable within the function scope or pass it as an argument to the function:

    var logIt = function (){
        var text = 'outside';
        console.log(text);
        text = 'inside';
    };
    logIt();
    

    or

    var text = 'outside';
    var logIt = function (txtArg){
        console.log(txtArg);
        var text = 'inside';
    };
    logIt(text);