forfearofthesun
forfearofthesun

Reputation: 3

Global variable undefined - scope issue

When running the following code, I expected the alert at the end of the function to use the globally defined variable value for "a" (1), but it instead returns undefined. If the code within the if block is never run, why does the the variable "a" return as undefined?

var a = 1;
four();

function four() {
  if (false) {
    var a = 4;
  }

  alert(a); //alerts undefined
}

Does the javascript parser "see" the variable declaration within the scope of a conditional expression in the same way that it would "see" it outside of that?

Upvotes: 0

Views: 111

Answers (2)

Brodie
Brodie

Reputation: 8737

Since variable declarations are 'hoisted' to the top of their scope, the second var a is being set inside of the function scope. so essentially it's turning into something like:

function four() {
  var a;

  if (false) {
    a = 4;
  }

  alert(a); //alerts undefined
}

if you were to remove the second assignment within the four function you would alert the window.a variable rather than the four.a one.

ie:

var a = 1;

function four() {
  if (false) {
    a = 4;
  }

  alert(a); //alerts 1
}

Upvotes: 2

SLaks
SLaks

Reputation: 887459

Yes.

All Javascript variable (and function) declarations are "hoisted" to their containing function.

The a local variable exists throughout your function (even before the if), but will only have a value after it's assigned.

Upvotes: 0

Related Questions