I read a lot of posts and ask/answer about javascript anonymous self-executing functions, but I’m afraid I’m still missing the point. Why does this code show myvar value? Shouldn’t the construct (function(){ code })() keep all variables not visible from outside?
(function(){
myvar = 5;
})();
alert(myvar);
so what’s the difference betwen above code and
function myfunction(){
myvar = 5;
};
myfunction();
alert(myvar);
?
Variables are scoped at the function level in javascript. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.
In your case, your myVar is available to the whole window as somebody pointed out already.
If you need to explicitly cage your variable inside a function scope, create an anonymous function and then execute it straight away and all the variables inside will be scoped to the function
results “undefined”