Break; and continue; in javascript loops


1 of July2008

Break; and continue; statements are essential when working with complex loops. They can be very useful. You can use them to end a loop prematurely, or skip the rest of the loop to start over at the beginning. Here is how you implement it:

<script type="text/javascript">
//build our array
var array1 = new Array();
array1[0] = 0;
array1[1] = 1;
array1[2] = 2;
array1[3] = 3;
array1[4] = 4;

var numArray = array1.length;
for(var i=0; i<numarray ; i++){
	if (array1[i] == 2){
		continue; //skip to the end of the for loop, then start over after incrementing by 1
	}else if (array1[i] == 3){
		break; //end the for loop, and execute code after the loop
	}

	alert("still in for loop: " + i);
}
	alert("after for loop: " + i);
</script>

The above code should have created popups for the numbers “0″, “1″, and “3″. This is because the “continue;” statement makes the code skip to the end of the loop, not executing any of the rest of the loop code, then starts over at the beginning of the loop after incrementing i by 1.

The “break;” statement causes the loop to end and the code after the loop to be executed. i is NOT incremented anymore and thus remains at 3.

You can also use “return;” to just end a function prematurely.

Add Your Own


bluehost.com ad


Recent Posts

  • Lessons learned from Apple&#39;s Design Process
  • On why I started another Redesign when I had just finished one.
  • Why I chose Bluehost for cheap, reliable hosting (review)
  • Break; and continue; in javascript loops
  • Writing a prototype function in JavaScript
  • -->