Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope).
If we use this definition from the MDM and apply it to your basic example and run it in a browser (no JSBin or JSFiddle).
<html>
<head></head>
<body>
<script>
var outer = 2;
var addTo = function() {
var inner = 3;
return outer + inner;
};
console.dir(addTo);
</script>
</body>
</html>
If we take a look at the console, you'll get the following output:

There is no closure like on JSBin and it's the expected behavior. We don't have any variable used locally but defined in an enclosing scope. outer
is defined in the global scope and not in an enclosing scope.
Now, if we use the exact same code but insert it in a self-executing anonymous function:
<html>
<head>
</head>
<body>
<script>
(function (){
var outer = 2;
var addTo = function() {
var inner = 3;
return outer + inner;
};
console.dir(addTo);
})();
</script>
</body>
</html>
The console output will be the following:

outer
is no longer defined in the global scope but inside an enclosing scope, the scope of the self-executing anonymous function and is use locally in the addTo
function. According to the definition, it is a Closure.
Regarding JSBin and JSFiddle, both of these sites will execute your code in a iframe for security reasons. On JSBin, the iframe looks like this with your code:
<body>
<script>
try {var outer = 2;
var addTo = function() {
var inner = 3;
return outer + inner;
};
window.runnerWindow.proxyConsole.dir(addTo);
} catch (error) { throw error; }
</script>
</body>
If we take a look at outer
, it's not defined in an enclosing scope. try
does not define a scope here since JavaScript has function scope but not block scope. As expected and as proven by your tests, there is no Closure element in the console.
JSFiddle, on the other hand, use a different code in his iframe to execute your code:
<head>
<script type="text/javascript">
window.onload=function(){
var outer = 2;
var addTo = function() {
var inner = 3;
return outer + inner;
};
console.dir(addTo);
}
</script>
</head>
On JSFiddle, your code is wrapped in an anonymous function which will be executed on the onload
event of the window. Your outer
variable is in this case a locally used variable defined in an enclosing scope and is a closure. That's why when you took a look at your console, you saw a Closure in the output.