I was recently playing around with labels and blocks (as one does) and found that they could be used as a way to annotate/contain chunks of JavaScript without using ugly comments (or abstraction?). I can see its appeal – it offers a sense of containment that is hard to get with just comments.

I’ll use the example of a really simple “getJSONP” function:

// BEFORE
function getJSONP(url, success) {
 
    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.head || document.getElementsByTagName('head')[0]
                             || document.documentElement;
 
    window[ud] = function(data) {
        head.removeChild(script);
        delete window[ud];
        success && success(data);
    };
 
    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);
 
}
 
// AFTER
function getJSONP(url, success) {
 
    declareVars: {
        var ud = '_' + +new Date,
            script = document.createElement('script'),
            head = document.head || document.getElementsByTagName('head')[0]
                                 || document.documentElement;
    }
 
    defineCallback: {
        window[ud] = function(data) {
            head.removeChild(script);
            delete window[ud];
            success && success(data);
        };
    }
 
    addScriptToDocument: {   
        script.src = url.replace('callback=?', 'callback=' + ud);
        head.appendChild(script);
    }
 
}

You may think that doing this borders on totally pointless and in this instance I’d probably agree, but you must admit it could potentially be useful in other situations (none come to mind though).

We’re normally used to { and } being used to delimit an object literal, but they can also be used to create blocks (or “compound statements”). A compound statement is a statement that contains any number of sub-statements. We use them all the time:

while (true) normalStatement;
while (true) {
    iAmInACompoundStatement;
    soAmI;
    ermICallItABlock;
}

We use them everywhere, if statements, for statements, while statements, switch statements, try/catch statements …

Since JavaScript doesn’t have block scope, using a block anywhere other than in the conventional places (if/while etc.) is almost totally pointless. However, as I mentioned, we could use them to annotate and contain logically related pieces of code:

definingMyVar: var x = 123;
 
definingABunchOfVars: {
    var x = 123,
        y = 456,
        z = 789;
}

We can even use break within these blocks:

var x = 1;
 
foo: {
    x = 2;
    break foo;
    x = 3;
}
 
x === 2;

Note that the break statement must include a label, otherwise it’s invalid; unlabelled break/continue statements are only permissible within switch statements and loops.

I dare say this is all quite pointless… but very interesting nonetheless. What say you?

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!