Reputation:
I'm finding myself by Javascript's variable scope, could someone explain to me why the first example doesn't work but the second does?
function test() {
return typeof(the_variable) !== 'undefined' && the_variable;
}
(function () {
var the_variable = "doesn't work";
console.log(test());
}());
var the_variable = "does work";
console.log(test());
Output I get in my log:
false
does work
Also I would like to know how to do something similar to the first example.
Upvotes: 0
Views: 192
Reputation: 12496
In Javascript, functions define scope. In your first example the_variable
is outside of the scope of test
. On the other hand, in the second example, the_variable
is defined in the global scope and is available everywhere.
EDIT
Catch the_variable
in a closure if you want it to be available to test
.
var foo = (function () {
var the_variable = "does work";
function test() {
return typeof(the_variable) !== 'undefined' && the_variable;
}
return {test : test};
}());
console.log(foo.test());
Output:
does work
Upvotes: 0
Reputation: 943569
Explained in comments:
function test() {
return typeof(the_variable) !== 'undefined' && the_variable;
}
// The variable in this function is scoped to the anonymous function.
// It doesn't exist outside that function, so `test` cannot see it
(function () {
var the_variable = "doesn't work";
console.log(test());
}());
// This variable exists in a scope that wraps the `test` function, so it can see it.
var the_variable = "does work";
console.log(test());
Upvotes: 6