Question

Currently I am getting the result undefined and I don't understand why that is.

var variable = "top-level";

function parentFunction() {
  function childFunction() {
    alert(variable);
  }
  childFunction();
  var variable = "local";
}

parentFunction();

I thought that because I declared the variable

var variable = "local";

after I called childFunction(), it would look up the scope chain and get the top level variable instead, but it seems that this isn't the case.

Was it helpful?

Solution

That happens because of hoisting, which is putting all var statements at the top of the function, but still executes the assignment statement at the line it was made. If you have a look below, the second var variable will shadow the global variable since it declares a local variable with the same name. Then, this newly declared variable will be undefined until it reaches the assignment line.

Basically, here's what your code does:

var variable = "top-level";

function parentFunction() {
  var variable;
  function childFunction() {
    alert(variable);
  }
  childFunction();

  variable = 'local';

}

parentFunction();

OTHER TIPS

All the variable declaration statements will be moved to the top of the function in which they are declared, but the values will be assigned to them only when the control reaches the declaration/initialization statement. In your case, childFunction doesn't have variable, so it goes up in the scope and checks the parentFunction, where variable is declared but not assigned a value yet. So, it alerts the default value undefined.

This is called variable hoisting.

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