---
title: "Functional scope in Javascript"
description:
  "What is functional scope. This blog discusses that in the context of
  JavaScript."
canonical_url: "https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me"
markdown_url: "https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me.md"
---

# Functional scope in Javascript

What is functional scope. This blog discusses that in the context of JavaScript.

- Author: Neeraj Singh
- Published: June 30, 2009
- Categories: jQuery

Javascript continues to surprise me. Check out this code.

```javascript
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.

```javascript
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.

## Links

- [Human page](https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me)
