Functional scope in Javascript

Neeraj Singh

Neeraj Singh

June 30, 2009

Javascript continues to surprise me. Check out this code.

function foo() {
  var x = 100;
  alert(x);

  for (var x = 1; x <= 10; x++) {}

  alert(x);
}

foo();

What do you think the value of second alert will be. I thought it would be 100 but the answer is 11. That's because the scope of a local variable in Javascript is not limited to the loop. Rather the scope of a local variable is felt all over the function.

Before you look at the next piece of code remember that defining a variable without the var prefix makes that variable a global variable.

fav_star = "Angelina"; /* it is a global variable */

function foo() {
  var message = "fav star is " + fav_star;
  alert(message);

  var fav_star = "Jennifer";
  var message2 = "fav star is " + fav_star;
  alert(message2);
}

foo();

What do you think would be the alert value first time? I thought it would be Angelina but the correct answer is undefined. That is because it does not matter where the variable is defined. As long as the variable is defined anywhere within a function then that variable will be set to undefined. It is when the statement is executed then the value of the variable changes from undefined to Jennifer.

Thanks to my friend Subba Rao for bringing this feature of Javascript to my attention and for discussing it.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.