Beautiful JS

JavaScript that belies the common conception of beauty

Looping with freedom

Loops don’t have to look like this:

for (var i = 0; i < array.length; i++) {}

… that’s how boring people write loops. “But”, you say, “That’s convention and therefore is the most readable format”.

True, but let’s be honest: variations of the above aren’t exactly challenging to grasp, and once you know a truthy expression from a falsey one, and the difference between prefix (++i) and postfix (i++) incrementers, there really is no point in holding back.

You don’t have to be entirely conventional.

for (var i = 0, l = a.length; i < l; i++); // cached length
for (var i = -1, l = a.length; ++i < l;); // bundled condition (increment+test)
for (var i = a.length; i--;); // reverse loop 
// The body of the loop makes changes that'll affect
// the evaluation of the condition. E.g. removing nodes:
while (node.firstChild) {
    node.removeChild(node.firstChild);
}
// Do something with node and its following siblings
do { } while (node = node.nextSibling);

A loop’s body is expendable too:

while (
    div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
    all[0]
);

That last one’s from here: https://gist.github.com/527683

Posted by James on 02 Oct 2011 | linky

Subscribe or follow @Beautiful_JS! | Fork then send a pull request to contribute.

Disclaimer: Beautiful code is readable, maintainable and scalable. It's not just nice to look it.