Breaking Out of a Loop

The break command, which you saw to be important inside a switch statement, is also available within for loops. You might need to use this, for example, when searching for a match of some kind. Once the match is found, you know that continuing to search will only waste time and make your visitor wait. Following Example shows how to use the break command.

<script>
haystack = new Array()
haystack[17] = "Needle"
for (j = 0 ; j < 20 ; ++j)
{
if (haystack[j] == "Needle")
{
document.write("<br />- Found at location " + j)
break
}
else document.write(j + ", ")
}
</script>