tags:

views:

77

answers:

3

Hi all, i have encountered the following curious piece of code:

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

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!

+8  A: 

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.

Dmitri Farkov
No. Local variables are very much valid after function execution. That's the reason **Javascript has closures**.
kangax
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
+2  A: 

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

You want

var works = ...
olliej
+3  A: 

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.

Pascal MARTIN