Take the 2-minute tour ×

i have encountered the following curious piece of code:

function foo(){
    works = {hello:"world"};
    function bar(){
    	alert('does not work');
    var notwork = {hello:"world"};

Can someone please explain to me why works work, and notwork doesn't work? Or point me out to a good resource that explains this in detail.

Thank you very much!

share|improve this question
add comment

3 Answers

up vote 11 down vote accepted

var notwork creates a local variable valid only for the runtime of the function.

works creates a global variable that is valid throughout the javascript runtime.

share|improve this answer
No. Local variables are very much valid after function execution. That's the reason Javascript has closures. –  kangax Sep 21 '09 at 23:47
As much as I agree, in this example the variable is NOT valid after function execution. Correct me if I am wrong, thanks! –  Dmitri Farkov Sep 22 '09 at 12:17
add comment

var declares a variable as "local" to the function it's defined in.

Without var, you works variable is global : it can be seen/accessed/used from anywhere.

With var, your notwork variable is local to the foo function : it cannot be seen/used from outside of that function.

For more informations, you can take a look at the documentation of the var statement on MDC, which states (quoting) :

The scope of a variable is the current function or, for variables declared outside a function, the current application.

Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable.
However, it is recommended to always use var, and it is necessary within functions in the following situations:

  • If a variable in a scope containing the function (including the global scope) has the same name.
  • If recursive or multiple functions use variables with the same name and intend those variables to be local.

Failure to declare the variable in these cases will very likely lead to unexpected results.

share|improve this answer
add comment

You've missed out the var keyword so works is being defined on the global object.

You want

var works = ...
share|improve this answer
add comment

Your Answer


