Take the following function:
function createGlobalVar() {
y = "foo";
}
y //"foo"
in the absence of the keyword 'var', which would make y a local variable, the function climbs up the scope chain to try and find where y exists. Without any pre-existing declaration, it creates y as a global variable. Thus I don't need to add 'return y' at the end of my function in order for y to exist outside of it.
Now if I try to do the same thing, but assign a function expression to y, it won't work.
function createGlobalVar() {
y = function() { alert("foo!") }
}
y //"undefined"
I know how to correct it to make it work:
function createGlobalVar() {
y = function() { alert("foo!") }
return y;
}
var x = createGlobalVar();
x // function() { alert("foo!") }
But I don't understand WHY I have to return the global variable just because a functional expression was assigned to it. What's different?