Tutorials

Learn web design and programming with our free video and text tutorials.

Javascript break Loops Tutorial

In javascript, you can sometimes get stuck in a loop. This is called an infinite loop.

Javascript allows you to break out of an infinite loop with the use of the "break" keyword. When javascript encounters the break keyword, it cases the javascript to stop executing the loop and executes the first statement that comes after the loop.

The javascript below shows the break keyword in action.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>

</head>
<body>

<script type="text/javascript" language="javascript">

count = 1;
while (count<=10)
{
if (count == 8)
break;
document.write("I can count to " + count + "<br />");
count++;
}

</script>

</body>
</html>

The javascript code above displays: