3

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?

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
bachposer
  • 953
  • 3
  • 8
  • 17

2 Answers2

5

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • to clarify, any var declarations get hoisted to the top of the function. the actual assignment occurs on the line it is written. you are re-declaring the variable to be a local variable instead of using the global variable because you used the keyword var. if you had not re-declared ctry with the keyword var, it would have worked as you expected it using the global variable instead. – dqhendricks Jul 17 '12 at 22:20
  • Yes it is. I thought function definitions get hoisted but did not know about the var declarations (local variables) getting hoisted as well. Thank you – bachposer Jul 17 '12 at 23:25
2

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.

cambraca
  • 27,014
  • 16
  • 68
  • 99