‘continue’ versus ‘else if’

When looping over an array and taking different actions based on the the contents of each array entry the traditional approach is to use an ‘if’ with an ‘else if’. I think that, in these circumstances, code becomes more readable if we use an ‘if’ with a ‘continue’.

Let’s take a list of things (we’ll do this in javascript)

var fooBar = ["foo","bar"];

and loop over it using ‘continue’

for (var x=0; x<=fooBar.length;x++){
    if (fooBar[x] === "foo"){
        console.log("we have foo");
        continue;
    }
if (fooBar[x] === "bar"){
    console.log("we have bar");
    }
}

and then lets loop over it again, this time using ‘else if’

for (var x=0; x<=fooBar.length;x++){
    if (fooBar[x] === "foo"){
        console.log("we have foo");
    }
    else if (fooBar[x] === "bar"){
        console.log("we have bar");
    }
}

I like the ‘continue’ snippet. It’s just that little bit easier for me to read. That little bit more explicit. The paths through the code are clearer to the naked eye.

js.perf suggests that using “continue” instead of “else if” within a “for” loop introduces a minimal, barely noticeable performance dip:
http://jsperf.com/continue-vs-else/2

I’m a ‘continue’ man from now on.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s