Understanding JavaScript Closures

In JavaScript, a closure is a function to which the variables of the surrounding context are bound by reference.

function getMeAClosure() {
    var canYouSeeMe = "here I am";
    return (function theClosure() {
        return {canYouSeeIt: canYouSeeMe ? "yes!": "no"}; 
    });
}

var closure = getMeAClosure();
closure().canYouSeeIt; //"yes!"

Every JavaScript function forms a closure on creation. In a moment I’ll explain why and walk through the process by which closures are created. Then I’ll address some common misconceptions and finish with some practical applications. But first a brief word from our sponsors: JavaScript closures are brought to you by lexical scope and the VariableEnvironment

Continue reading

Compose: functions as building blocks

As regular readers have probably noticed, a recurring theme of these posts is function manipulation as an expressive device. JavaScript treats functions as first class objects, that is they can be created and modified dynamically and passed as data to other functions and objects. Shamelessly continuing this theme, allow me to introduce functional composition…

Here’s a couple of simple examples to start:-

var  alertPower = alert.compose(Math.pow);
alertPower(9,8); //alert shows 43046721
var  roundedSqRoot = Math.round.compose(Math.sqrt);
roundedSqRoot(28); //5

Continue reading

Curry: cooking up tastier functions

Currying allows you to easily create custom functions by partially invoking an existing function. Here’s a simple example:

var add = function(a,b) {
    return a + b;
}

var addTen = add.curry(10); //create function that returns 10 + argument
addTen(20); //30

Generally, curry returns a copy of the invoking function, with its first n arguments pre-assigned with the arguments passed by the curry invocation.

Continue reading