0

I am having a bit of trouble understanding the lifetime of global variable x below. I have commented my question on the line that I am not understanding.. please help... thanksss

var target = document.getElementById("outputArea");
var outString = "";

var x = 0;
var y = 0;

callMeOften2();
callMeOften2();
callMeOften2();
outString += "<br/>";

target.innerHTML = outString;

function callMeOften2() {
    outString += x + "<br/>"; //why isn't this going to give an output of 0? but gave an output of undefined instead? isn't x referring to the global variable x?
    var x = 100;

    x = x + 100;
    outString += "from callMeoften2: " + "x = " + x + "<br/>";
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87

1 Answers1

0

Here is how all Javascript Engines through variable hoisting plays with your code (effectively)

function callMeOften2() {
    var x = undefined;
    outString += x + "<br/>"; //why isn't this going to give an output of 0? but gave an output of undefined instead? isn't x referring to the global variable x?
    x = 100;

    x = x + 100;
    outString += "from callMeoften2: " + "x = " + x + "<br/>";
}

Hope this helps

The var x in the function means the global x is irrelevant (of course can be accessed using window.x in a browser, ro some other "global" object in other environments)

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • How does the JVM enter into this? – Ismail Badawi Oct 07 '15 at 00:06
  • sorry, bad term - not sure why I recently started referering to Javascript Engines as JVM's!! I keep doing it too! I hate Java almost as much as I hate JQueery!! – Jaromanda X Oct 07 '15 at 00:07
  • To be fair though, JVM can be an abbreviation of Javascript Virtual Machine, which is a thing, so, Java programmers will just have to suffer in silence – Jaromanda X Oct 07 '15 at 00:12
  • so whenever a variable which has the same name as global variable is declared in a function... no matter what location.. when the variable is mentioned even before the local variable is declared... then.. this variable is still referring to the not yet declared local variable? – stackoverflow___acc1 Oct 07 '15 at 00:20
  • a variable declaration is hoisted to the top of the current scope. what exists in other scopes is irrelevant – Jaromanda X Oct 07 '15 at 00:36
  • ohhh i see! thanks.. makes a lot more sense :D – stackoverflow___acc1 Oct 07 '15 at 00:46