Tag: for

Rethinking JavaScript for-loops

(versión abreviada en español)

If you think the introduction of Array.prototype.forEach and friends will send the for-loop the way of the dodo, think again. There’s life in the old dog yet.

The for-loop is often seen as something of a one trick pony, most suited to the classic form of list iteration:

for (var i=0; i<arr.length; i++) {
    //do something to each member
}

but with the wealth of higher order functions now available both natively and in frameworks we can just do this (or variants thereof)

arr.forEach(function(each)) {
    //do something to each
});

Ironically as high-order functions gradually render the traditional pattern obsolete, so might we become liberated from our old habits and branch out to explore more interesting patterns of for-looping.

To whet your appetite – here’s an ultra-compact way to generate and alert the first n members of the Fibonacci series:

for (
    var i=2, r=[0,1];
    i<15 || alert(r);
    r.push(r[i-1] + r[i-2]), i++
);
//alerts "0,1,1,2,3,5,8,13,21,34,55,89,144,233,377"

 
Continue reading “Rethinking JavaScript for-loops”

No ifs…alternatives to statement branching in JavaScript

You could do this..

//Example 1
function getEventTarget(evt) {
    if (!evt) {
    	evt = window.event;
    }
    if (!evt) {
    	return;
    }
    var target;
    if (evt.target) {
        target = evt.target;
    } else {
        target = evt.srcElement;
    }
    return target;
}

or you could do this…

//Example 2
function getEventTarget(evt) {
    evt = evt || window.event;
    return evt && (evt.target || evt.srcElement);
}

Continue reading “No ifs…alternatives to statement branching in JavaScript”