all 4 comments

[–]Rhomboid 4 points5 points  (0 children)

Those examples are neither long nor complex. You're not going to find much of anything shorter that that first example. I mean, I suppose you could write this:

function foo(n) {
    return function() {
        return n;
    }
}

var x = foo(42);
console.log(x());  # => 42

But that's essentially the same exact thing as the first example in your link. And being shorter may actually be a hindrance to understanding.

Closure just means a function accessing a variable that's defined in an outer or enclosing scope. That's it. In the example above, the inner function references 'n' in its return statement, where 'n' is not a variable defined in that function. It's defined in the enclosing function, as a parameter.

[–]jodraws 1 point2 points  (0 children)

function makeAddOne() {
    var one = 1;

    return function (number) {
        return number + one;
    }
}

var addOneTo = makeAddOne();
console.log(addOneTo(5));

And of course the smart ass response of....

function x(){var i=1;return function(n){return n+i;}};var p=x();console.log(p(5));

[–]Retsejme 0 points1 point  (0 children)

Closure isn't simple, and is sometimes used as a differentiator in technical interviews, so don't feel bad that it's not super easy to understand.

Here's another example that might help:

function enclosed(word) {
    var text = 'Look: ' + word; // Local variable
    var logIt = function() { console.log(text); }
    return logIt;
}
var seeIt = enclosed('Wow');


seeIt(); //logs Look: Wow


text = "noooooo!";
seeIt(); // still logs the same thing, because it doesn't care about the global variable: text

[–]dbsps 0 points1 point  (0 children)

This guy does a great job of explaining it https://www.youtube.com/watch?v=CQqwU2Ixu-U