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);
5  for (var x = 1; x <= 10; x++) {}
7  alert(x);

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 */
3function foo() {
4  var message = "fav star is " + fav_star;
5  alert(message);
7  var fav_star = "Jennifer";
8  var message2 = "fav star is " + fav_star;
9  alert(message2);

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.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.