I have the following code
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
How to access myVar within #second ?
It depends on the wider context of your code. You can do this:
(function() {
var myVar;
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
})();
That creates an anonymous function and calls it right away. The purpose of the anonymous function is to provide a container for myVar without making myVar a global variable. Global variables are generally best avoided (not least because they become properties of the window object, which already has all sorts of junk stuck on it). Specifically, the functions you're assigning to your click and blur events become closures over the data inside the call to the anonymous function. They have access to myVar, but nothing else does. More here.
If your code is already inside a containing scope, or you don't care about adding to the global namespace, you don't need the anonymous function.
(function(){})() instead of (function(){}()). The latter seems much more natural to me. The outer parenthesis are not needed either, but they signalize something secial going on.function(){}(); unreliable. The parens around the function expression are required in some edge cases. This doesn't apply to just using a function expression or even to accessing its properties (function(){}.call(...); works just fine, for instance), it has to do with the parens triggering the call. Example: jsbin.com/ecuba3 On Chrome, that fails with an "unexpected token" error. Add the parens and it works: jsbin.com/ecuba3/2 (Actually, given how simple that is, maybe it's not an "ambiguity".)(function(){}()) works as expected. I perfer this method and i discovered that Doug Crockford writes his code like this, as well.T.J. Crowder's answer does what you want. This is just an alternative (using the jQuery data storage methods):
$('#first').click(function() {
// Assign this element to have data with the key 'myVar'
$(this).data('myVar', $(this).next().val());
});
$('#second').blur(function() {
// Read the data from the other element
console.log($('#first').data('myVar'));
});
The answers here are good. But I think you're at the point where you'd benefit from reading Crockford's JS slideshow. It's very good and explains several matters related to your question.