Question

I have a .js file that I am executing with NodeJS. Here are the contents of my file:

var ctry = "America";

function outer(msg) {
    console.log(msg + " " + ctry) ;
    var ctry = "Canada" ;
}
outer("God Bless");

When I run this file, I expect to see "God Bless America" but instead, I see "God Bless undefined".

If I comment out the inner var ctry = line I get "God Bless America" and if I move the inner var ctry = line above the console.log, I get "God Bless Canada". These last two cases seem logical but why does the very definition of var ctry after the console.log cause ctry to be set to underfined in the code above?

Was it helpful?

Solution

The scope of a local variable (ctry in your case) is the whole of the function in which it is declared (that is, as if the variable were declared at the top of the function). Your code above is semantically the same as:

function outer(msg) {
    var ctry ;
    console.log(msg + " " + ctry) ;
    ctry = "Canada" ;
}

It should be clear now why you get undefined in the output.

OTHER TIPS

When you say var ctry inside a function (it doesn't matter where as long as it's inside the function), then what happens is that any calls to ctry made inside the function (again, doesn't matter where) will reference the inner variable, not the global one. The issue is, the JS interpreter only sees a definition of a variable, but doesn't initialize it with the value (Canada) until it executes that line, so in console.log it is yet undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top