The reason the second example works is because you define myvar as a global variable (accessible from anywhere).
The first example does not work because the variable is defined within the functional scope (which means that it is not available to everyone except that scope of the function and the scope of functions defined within this parent function).
As stated in the comments, this is how JavaScript works. If this is a problem you are facing, then you will probably need to rethink your architecture.
One common pattern is to define shared variables as properties of parent objects or functions. For instance:
$(function() { var funcOne = function() { this.sharedVal = 'stack overflow'; }; var funcTwo = function() { console.log(funcOne.sharedVal); }; });
Thus, you can have different functions that can share their properties from another in other functions, while maintaining a global namespace. Note, however, that in this example, simple var x = 'something'; , which is not bound as a property of another function, will do the same.
source share