The reason the second example works is because you're defining myvar
as a global variable (which is accessible from anywhere).
The first example doesn't work because the variable is defined within functional scope (meaning it's inaccessible from all except that function's scope, and the scope of functions defined within that parent function's scope).
As stated in the comments, this is just how JavaScript works. If this is a problem you're running into then it's probably time to rethink your architecture.
One common pattern is to define shared variables as properties of parent objects or functions. For example:
$(function() {
var funcOne = function() {
this.sharedVal = 'stack overflow';
};
var funcTwo = function() {
console.log(funcOne.sharedVal);
};
});
This way you can have distinct functions that are able to share their properties from within other within other functions, whilst also keeping the global namespace clean. Note, however, that in this example, a simple var x = 'something';
which isn't bound as a property of another function would do just as well.