Functional scope in Javascript

Neeraj Singh

By Neeraj Singh

on June 30, 2009

Javascript continues to surprise me. Check out this code.

1function foo() {
2  var x = 100;
3  alert(x);
4
5  for (var x = 1; x <= 10; x++) {}
6
7  alert(x);
8}
9
10foo();

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.

1fav_star = "Angelina"; /* it is a global variable */
2
3function foo() {
4  var message = "fav star is " + fav_star;
5  alert(message);
6
7  var fav_star = "Jennifer";
8  var message2 = "fav star is " + fav_star;
9  alert(message2);
10}
11
12foo();

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.