Variable visibility

Hi - I am trying to better understand scope to do with ‘self-executing anonymous functions’, as I understand that - no variables declared inside of the function are visible outside of it.

How about variables inside of an self-executing anonymous function ( or just an anonymous function for that matter ), but declared without the ‘var’ keyword.

Can they also not be accessed outside of the self-executing anonymous function ( or a plain anonymous function ).

Variables can’t be declared without the var keyword. I’m not sure what you’re asking then. See, you can declare & define a variable outside of the SEAF and then use it within the function, but you wont be able to get that value outside of the function.

Check this out for some great info on self-executing anonymous functions: How Self-Executing Anonymous Functions Work | Brian Crescimanno

I was looking at a jQuery Fundamentals, PDF, from the internet, and their it mentioned when talking about SCOPE :

If the variable wasn’t previously defined, it will be defined in the global scope,

Then it went onto give an example :

var myFunction = function() {
var foo = 'hello';
var myFn = function() {
console.log(foo);
};
foo = 'world';
return myFn;
};
var f = myFunction();
f(); // logs 'world' -- uh oh

And then it illustrated how ‘bar’ can be accessed from the outside because it was defined without the ‘var’ keyword :

// a self-executing anonymous function
(function() {
var baz = 1;
var bim = function() { alert(baz); };
bar = function() { alert(baz); };
})();
console.log(baz); // baz is not defined outside of the
function
bar(); // bar is defined outside of the anonymous function
// because it wasn't declared with var;
furthermore,
// because it was defined in the same scope as baz,
// it has access to baz even though other code
// outside of the function does not
bim(); // bim is not defined outside of the anonymous
function,
// so this will result in an error

But after doing some novice coding I found that a simple variable if defined within an anonymous function without the var keyword cannot be accessed from the outside…

[RIGHT].
[/RIGHT]

I think know where I was getting mixed up. But It has clarified another issue for me that is variables declared within a callback should be within an enclosure or otherwise you will get unpredictable results.