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?
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.