Reputation: 15156
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
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 usevar
, 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
Reputation: 36773
You've missed out the var
keyword so works
is being defined on the global object.
You want
var works = ...
Upvotes: 2
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