continue – the forgotten statement

Share this article

I’m a big fan of continue, partly just because it’s a positive and encouraging word (carry on, everything’s fine), but mostly because it can reduce code and improve efficiency, and that’s almost always a good thing.

Here’s a quick precis: the continue statement can be used within an iterator, such as a for loop, and means continue to the next iteration; this is contrast to the break statement which means abandon this loop entirely.

So, whenever the code inside an iterator is finished for that iteration, we can use the continue statemtent to prevent the interpretor from reading unecessary code, and to reduce the actual amount of code we have to type.

For example, this code:

for(var i=0; i<ary.length; i++)
{
	if(ary[i] == 'foo')
	{
		//something
	}
	
	else
	{
		//whatever
	}	
}

Could also be written like this:

for(var i=0; i<ary.length; i++)
{
	if(ary[i] == 'foo')
	{
		//something
		
		continue;
	}

	//whatever
}

I’m also a big fan of continue as a means to jump past conditions we’re never interested in, such as ignoring external prototypes when iterating through the properties of an object; so rather than this:

for(var i in obj)
{
	if(obj.hasOwnProperty(i))
	{
		//whatever
	}
}

We can do this:

for(var i in obj)
{
	if(!obj.hasOwnProperty(i)) { continue; }

	//whatever
}

So what’s the real difference? Well, we’ve avoided the need for a braced condition, which can make the code more efficient (since the interpretor doesn’t have to evaluate that condition), and I think it also makes the code easier to read — every level of bracing introduces an extra piece of cognitive load, and reducing them is desirable simply for that reason. The continue statement is a means of avoiding such conditions in iterative code, and that’s why I like them so much.

James EdwardsJames Edwards
View Author

James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form