FurtiveFelon
FurtiveFelon

Reputation: 15156

scope in javascript

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!

Upvotes: 1

Views: 190

Answers (3)

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

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.

Upvotes: 3

olliej
olliej

Reputation: 36773

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

You want

var works = ...

Upvotes: 2

Dmitri Farkov
Dmitri Farkov

Reputation: 9671

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.

Upvotes: 11

Related Questions