Repetition (Arrays and Loops)
References
- W3Schools JavaScript Array Reference
- W3Schools JavaScript do/while Statements
- W3Schools JavaScript for Statements
- W3Schools JavaScript for/in Statements
- W3Schools JavaScript break Statements
- W3Schools JavaScript continue Statements
Array Review
We saw Arrays in the e-handout "Data Types and Operators". Let's do a brief review of arrays.
Recall that an Array is a set of data represented by a single, indexed variable name.
Arrays are represented in JavaScript by the Array object, which contains a constructor function named Array( ). As with any other object in JavaScript, you create a new Array object with the new keyword, like this:
var hospitalDepartments = new Array(10);You should note that the numeric argument to the Array constructor function tells JavaScript how many items will be in the array. This argument is, however, optional. In JavaScript, you can add items (elements) to the array as needed, and JavaScript will automatically adjust the count of elements in the array.
Each item in an array is called an element.
The numbering of elements within JavaScript arrays starts with index number zero (0). You refer to a specific element of a JavaScript array by giving the array name followed by the index number enclosed in square brackets, like this:
hospitalDepartments[0] = "Anesthesia"; hospitalDepartments[1] = "Molecular Biology"; hospitalDepartments[2] = "Neurology"; hospitalDepartments[3] = "Oncology"; hospitalDepartments[4] = "Ophthalmology"; hospitalDepartments[5] = "Otolaryngology"; hospitalDepartments[6] = "Pediatrics"; hospitalDepartments[7] = "Psychiatry"; hospitalDepartments[8] = "Pulmonary Diseases"; hospitalDepartments[9] = "Radiology";
Once you have assigned a value to an array element, you can, just as with any other variable in JavaScript, change the value later if needed, like this:
hospitalDepartments[5] = "Prosthetics";
Most programming languages require that all of the elements in an array contain data of the same data type, but JavaScript does not limit you with this requirement. You can mix different data types in JavaScript arrays if you wish.
You can assign values to array elements when you first create the array, like this:
var hospitalDepartments = new Array ("Anesthesia", "Molecular Biology",
"Neurology");
The Array object contains various methods that we will not discuss here. But a very useful property of the Array object is the length property. The length property contains a value that tells you how many elements are in the array. For instance, you can display how many elements are in an array like this:
document.write("There are " +
hospitalDepartments.length +
" departments in this hospital.");
Associative Arrays
There is another form of array indexing in JavaScript, used with an array type called "Associative Arrays". In an associative array, the index is a string instead of a number.
Here is some code that shows how a string can be used as an array index in JavaScript:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Phone Book Demo</title>
<link rel="stylesheet" type="text/css" href="Samples.css">
<script type="text/javascript">
/* <![CDATA[ */
var phone_book = new Array();
phone_book["happy"] = "(203) 555-1111";
phone_book["sleepy"] = "(203) 555-2222";
phone_book["sneezy"] = "(203) 555-3333";
phone_book["sleezy"] = "(203) 555-4444";
phone_book["sneary"] = "(203) 555-5555";
phone_book["bleary"] = "(203) 555-6666";
phone_book["tweaked"] = "(203) 555-7777";
function displayNumber(the_phone_book, entry)
{
var the_number = the_phone_book[entry];
document.getElementById("number_box").value = the_number;
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<h1>The Dwarves of Multimedia Gulch</h1>
<form name="the_form" action="" method="post">
<table border="0" cellpadding="5" cellspacing="0">
<tr>
<td valign="top"><b>Name:</b></td>
<td valign="top">
<select onchange = "displayNumber(phone_book, this.options[this.selectedIndex].value);"
size="7">
<option value="happy">Happy</option>
<option value="sleepy">Sleepy</option>
<option value="sneezy">Sneezy</option>
<option value="sleezy">Sleezy</option>
<option value="sneary">Sneary</option>
<option value="bleary">Bleary</option>
<option value="tweaked">Tweaked</option>
</select>
</td>
<td valign="top"><b>Number:</b></td>
<td valign="top">
<input type="text" name="number_box" id="number_box" value="" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The onchange attribute in the <select> tag is an event handler like we saw in Handout 2. The Change event occurs in a select list when the user selects a different item than is currently selected.
- The keyword this refers to the JavaScript object that is created to represent the HTML item/element that it (this) appears in. So in this code, this refers to the select object.
- this.options refers to the JavaScript array that the <option> tags become elements in.
- this.selectedIndex is the index (0-based) of the currently-selected item in a selection list.
- The value property contains the value (what else?) of the form element that it represents in the HTML form, and can be changed with JavaScript code.
Below is a second example of an associative array. You should note carefully in this example that the length property has a value of 0 in an associative array:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Test Associative Arrays</title>
</head>
<body>
<div id="mainDiv">
<h3 style="text-align:center;">Testing Associative Arrays</h3>
<script type="text/javascript">
/* <![CDATA[ */
var myArray = new Array();
myArray["one"] = 100;
myArray["two"] = -1.35;
myArray["three"] = "Kangaroo";
for (stuff in myArray)
{
document.write("The value for index '" + stuff + "' is " + myArray[stuff] + "<br>");
}
document.write("The length property has a value of " + myArray.length);
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- We will see the for...in loop in another section of this handout, below. For now, you just need to know that it cycles/loops/iterates through all of the elements in an object or an associative array.
- During each iteration of the for...in loop, the variable stuff contains the index value (a string) for that item.
while Statements
The statements you have worked with so far, like the if statements and the switch statement, run in a linear fashion, top to bottom. If you need to repeat a statement, or a function, or other code sections multiple times, you need to use a loop statement such as a while loop. A loop statement repeatedly runs a statement or code block while a specific condition is true or until a specific condition becomes false.
The while statement is used for repeating a statement or code block as long as a given conditional expression evaluates to true.
The syntax of the while statement looks like this:
while (conditional expression)
{
statement;
statement;
...
}
Please note these points about the above syntax:
- The statement begins with the while keyword.
- The conditional expression is contained in parentheses.
- The statement(s) that you want repeated are contained in curly braces.
- If the conditional expression is initially false, the loop never runs its contained statements.
- If the conditional expression initially evaluates to true, the loop runs until the conditional expression becomes false. Then the loop ends, and any statements following the loop are run.
Each repetition of a looping statement is called an iteration.
You must make sure that the conditional expression will eventually evaluate to false. If it does not, you will have created what is called an infinite loop. An infinite loop will never stop looping. You really don't want to do this. If you do mistakenly create such a loop, however, you can usually stop the browser by using the CTRL+ALT+DELETE key combination to open the Windows Task Manager and stop the browser.
Here is a sample of code using a while statement:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>While Loop 1</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
var count = 1;
while (count <= 5)
{
document.write(count + "<br/>");
count++;
}
document.write("You have displayed " + (count - 1) + " numbers.");
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- As long as the count variable is less than or equal to 5, the loop will iterate.
- We avoided an infinite loop by incrementing the count varible inside the code that is repeated.
- When the count variable reaches a value of 6, the condition is false and the loop ends.
- Because the count variable is 6 when the loop ends, we subtract 1 from it in the line that displays "You have displayed..."
Another form of the while statement is shown below:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>While Loop 2</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
var keepGoing = true;
while (keepGoing)
{
document.write("A line...<br/>");
keepGoing = confirm("Press OK to keep going, or Cancel to stop");
}
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- Recall that the confirm( ) built-in method returns true if the user clicks OK, and it returns false if the user clicks Cancel.
- We have to set the keepGoing variable to true to being with, so the loop runs at least once.
- The conditional expression in this sample uses a shorthand
notation to test for the true value. It could have been
coded in the normal Conditional Operator format like this:
while (keepGoing == true)
but it is just as valid, and quite common in JavaScript, to use the shorthand syntax.
do...while Statements
The do...while statement executes a statement or group of statements once, then repeats the execution as long as the conditional expression evaluates to true. You should note carefully that the do...while statement always runs its contained statements at least once regardless of the initial value of the conditional expression.
The syntax of the do...while statement looks like this:
do
{
statement;
statement;
...
}
while (conditional expression);
Please note these points about the above syntax:
- The statement begins with the do keyword.
- The statement(s) that you want repeated are contained in curly braces.
- Following the contained statements is the while keyword.
- The conditional expression is contained in parentheses.
- There is a semi-colon after the conditional expression.
- The contained statements run at least once before the conditional expression is evaluated.
- If the conditional expression is initially false, the loop stops after the first iteration, but it does run once before it stops.
- If the conditional expression initially evaluates to true, the loop runs until the conditional expression becomes false. Then the loop ends, and any statements following the loop are run.
As with the while statement, with the do...while statement you must make sure that the conditional expression will eventually evaluate to false. If it does not, you will have created what is called an infinite loop. An infinite loop will never stop looping. You really don't want to do this. If you do mistakenly create such a loop, however, you can usually stop the browser by using the CTRL+ALT+DELETE key combination to open the Windows Task Manager and stop the browser.
Here is a sample of code using a do...while statement:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Do While Loop 1</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
var count = 1;
do
{
document.write(count + "<br/>");
count++;
} while (count <= 5);
document.write("You have displayed " + (count - 1) + " numbers.");
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The output of this code is the same as the first sample's in the previous section on the while loop.
- The first iteration of the document.write( ) statement always happens.
- As long as the count variable is less than or equal to 5, the loop will continue to iterate.
- We avoided an infinite loop by incrementing the count variable inside the code that is repeated.
- When the count variable reaches a value of 6, the condition is false and the loop ends.
- Because the count variable is 6 when the loop ends, we subtract 1 from it in the line that displays "You have displayed..."
The difference between while and do...while statements is more clearly seen in the following sample code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Do While Loop 2</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
var displayNum = prompt("Enter a number", "");
if ((displayNum == "") || (displayNum == null))
{
displayNum = 0;
}
do
{
document.write("The number is " + displayNum + "<br/>");
displayNum--;
}
while (displayNum > 0);
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The prompt( ) built-in method returns an empty string if the user fills in nothing and clicks "OK"; but it returns null (a JavaScript built-in keyword value) if the user clicks "Cancel".
- We want the "The number is" information to display at least once, even if the number starts at 0. This is the reason that we use the do...while statement here. If we had used a while statement with the same conditional expression, the information would never display.
Now, here is another version of the above code, which we modified in class in the Fall 2010 semester. We made these changes:
- We added a second variable, finalNum, to receive the value that we will display.
- We added an else statement.
- We added a test for the possibility that the decrement operator (--) could result in NaN (Not a Number), if the user types in some alphabetic characters, for instance.
This is file displayNumStuff.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Do While Loop 2b</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
var finalNum;
var displayNum = prompt("Enter a number", "");
if ((displayNum == "") || (displayNum == null))
{
finalNum = 0;
}
else
{
finalNum = displayNum;
}
do
{
document.write("The number is " + finalNum + "<br/>");
finalNum--;
if (isNaN(finalNum))
{
document.write("Oops, it's NaN!");
}
}
while ( finalNum > 0);
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
for Statements
The for statement is used to repeat a statement or a series of statements (code block) as long as a condition is true. This should sound familiar to you, since it is basically the same definition as that for a while statement. But in the for statement you can include code to initialize a counter and change its value in the for statement itself, instead of doing so in the code block.
Here is the basic syntax for the for statement:
for (initialization expression; condition; update statement)
{
statement;
statement;
...
}
Please note these points about the above syntax:
- The statement begins with the for keyword.
- The three items inside the parentheses are separated by semi-colons.
- The initialization expression runs only once, and is run when the for statement is first encountered. Usually this initialization expression creates (declares) a variable that is used as a counter.
- The condition (a conditional expression) is evaluated. Usually, this conditional expression checks the value of the variable that was created and initialized in the initialization expression. If the condition is true, the statement(s) in the associated code block are run.
- After the statement(s) in the code block are run, the update statement runs, changing the value of the variable that was created and initialized in the initialization expression.
- The condition is evaluated again. If the condition is true, the statement(s) in the associated code block are run again.
- Steps 5 and 6 continue to run until the condition evaluates to false. Then the for statement ends and any statements following it are run.
Technically, you can omit any of the three parts of the for statement constructor (the part inside the parentheses). But you must include the semi-colons even if you omit any of these three parts. And you must make sure you change the condition somehow in your code block, so you don't create an infinite loop!
Here is a sample of a for statement in action:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>For Loop 1</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
var fastFoods = new Array();
fastFoods[0] = "Pizza";
fastFoods[1] = "Burgers";
fastFoods[2] = "French Fries";
fastFoods[3] = "Tacos";
fastFoods[4] = "Burritos";
fastFoods[5] = "Fried Chicken";
fastFoods[6] = "Subs";
for (var count = 0; count < fastFoods.length; count++)
{
document.write(fastFoods[count] + "<br/>");
}
/* ]]> */
</script>
<h3>This is a sample of a <i>for</i> statement.</h3>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- Recall that the length property of an Array object returns the number of items (elements) that are in the array.
- The condition uses the less than operator (<) because arrays use index 0 for the first item. When the count variable is equal to the number of items in the array, it can no longer be used as an index for the array, because the index for the last item in an array is 1 less than the number of items.
-
The previous note brings us to another one of
Jim's Rules of Survival #3:
Use the < operator with the length property for most arrays in for loops.
In other words, <= is usually a bug!
- Some people like to use ++count in the update statement. I prefer count++. But either one is perfectly acceptable. Except in certain very technical situations, it's mostly a matter of taste, preference, and experience.
Here is another sample of a for statement in action. We saw the array in this sample in Assignment 3. But in that assignment, the displayed numbers did not have trailing zeroes. This sample adds a for loop to add the trailing zeroes, and another for loop to display the array items.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Interest Array with Formatting</title>
<script type="text/javascript">
/* <![CDATA[ */
function formattedNumber(theNumber, lengthNeeded)
{
var numberStr = theNumber.toString();
if (numberStr.length < lengthNeeded)
{
var numberZeroesNeeded = lengthNeeded - numberStr.length;
for (var j = 0; j < numberZeroesNeeded; j++)
{
numberStr += "0";
}
}
return numberStr;
}
var interestArray = new Array(7);
interestArray[0] = .0725;
interestArray[1] = .0750;
interestArray[2] = .0775;
interestArray[3] = .0800;
interestArray[4] = .0825;
interestArray[5] = .0850;
interestArray[6] = .0875;
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<h3>The values in interestArray are:</h3>
<script type="text/javascript">
/* <![CDATA[ */
for (var i = 0; i < interestArray.length; i++)
{
document.write(formattedNumber(interestArray[i], 6) + "<br />");
}
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The Number object, which is used for every number in JavaScript automatically, has a toString() method which converts the number to a string representation of the number.
- The String object, which is used for every string in JavaScript automatically, has a length property which contains a number which gives the number of characters in the string.
Why Arrays?
You now know enough to more fully understand the answer to the question, "Why should we use arrays?" Here is some code that illustrates part of the answer:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Why Arrays 2</title>
<script type="text/javascript">
/* <![CDATA[ */
var actors = new Array();
function writeTheActors()
{
var contentString = "";
for (var i = 0; i < actors.length; i++)
{
contentString += actors[i] + "<br />";
}
document.getElementById("contentDiv").innerHTML = contentString;
}
function askForActors()
{
var keepGoing = true;
var theActor;
while (keepGoing)
{
theActor = prompt("Give me the name of one of your favorite actors/actresses, please. Press Cancel or press Enter with nothing entered, when you are done.","");
if ((theActor != null) && (theActor != ""))
{
actors[actors.length] = theActor;
}
else
{
keepGoing = false;
}
}
writeTheActors();
}
/* ]]> */
</script>
</head>
<body onload="askForActors();">
<div id="mainDiv">
<h3>Favorite Actors/Actresses</h3>
<h4>Your favorites are:</h4>
<div id="contentDiv"></div>
</div>
</body>
</html>
You can see the "Why Arrays?" code running here.
Please note these points about the above code:
- The two custom functions are defined in the <head>...</head> section.
- The askForActors( ) function is called from the onload event handler.
- In this askForActors( ) function, the assignment statement
actors[actors.length] = theActor;
shows another ofJim's Rules of Survival #4:
Use the length property as the index in array assignments, for example: actors[actors.length] = theActor;
- The writeTheActors( ) function is called at the end of the askForActors( ) function.
- The previous two points mean that both functions are already in the browser's memory before either of them is called.
- The writeTheActors( ) function uses the innerHTML property of the <div>...</div> tag to display the list of actors. If the function were to use document.write( ) to display the list, it would replace the entire page's contents with the list. This is not what we want.
The last point in the above list mentions this feature of the document.write( ) built-in method: If document.write( ) is called after the page has completed loading, document.write( ) replaces the entire page contents, including all of the HTML tags. You can use this feature to re-write the page if you wish, beginning with the <html> tag, but this is a lot of work. It is usually better to replace the contents of a tag such as a <div>...</div> tag, using the innerHTML property. We will see this property again in future classes.
for...in Statements
Recall that the variables in an object are called properties.
The for...in statement is used to run some statements that do something with all of the properties within an object, one property at a time.
Here is the basic syntax for the for...in statement:
for (variable in object)
{
statement;
statement;
...
}
Please note these points about the above syntax:
- The variable will hold an individual property name for each loop through the object's properties. The variable is created by JavaScript simply by its being in the for (variable in object) clause.
- The object name must be an object that exists (has been created -- either automatically by the browser, or by your code).
- No counter is needed. JavaScript automatically loops through all of the properties in the object, assigns each property to the variable one at a time, runs the statements (code block), and continues to the next property, etc.
- The for...in statement ends after the loop has handled the last property in the object.
Here is a sample of a for...in statement in action:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>For...In Loop</title>
</head>
<body>
<div id="mainDiv">
<h3>The properties in the window object are:</h3>
<script type="text/javascript">
/* <![CDATA[ */
for (stuff in window)
{
document.write(stuff + "<br/>");
}
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The stuff variable holds the name of each property in the object, one at a time.
- The type of the variable stuff (using the typeof operator) when it contains a property name is string.
Recall, please, that you can use a string as an array index in JavaScript. This kind of array is called an "Associative Array".
The values of the properties in an object are stored as an associative array in that object. What this means for our current purposes is that you can use the name of each object property as the index to that property's value in the array which is the list of properties in the object.
Here is a sample of using a for...in statement to display the value of each property of an object. This code is very similar to the code just above, but this time we are making use of the associative array which stores the values of the various properties:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>For...In Loop</title>
</head>
<body>
<div id="mainDiv">
<h3>The values of the properties in the window object are:</h3>
<script type="text/javascript">
/* <![CDATA[ */
for (stuff in window)
{
document.write("The value of " + stuff + " is " + window[stuff] + "<br/>");
}
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
with Statements
Another statement that you can use to work with object properties (and methods) is the with statement. The with statement eliminates the need for you to type the name of the object over and over again in your code. When you put your statements that refer to an object's properties or methods within the code block of a with statement, you only have to type the name of the property or method.
Here is the basic syntax of the with statement:
with (object)
{
statement;
statement;
...
}
Please note these points about the above syntax:
- The name of the object that you want to reference in the code block is placed within the parentheses.
- The statement(s) that will reference the object are placed within the curly braces.
- You only have to type the name of whatever property or method you are referring to, not the name of the object, in the code block.
Here is an example of how you can use the with statement to shorten your code (and save typing):
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>With Statement</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
with (document)
{
write("This is line 1.<br/>");
write("This is line 2.<br/>");
write("This is line 3.<br/>");
}
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
-
The write( ) method is contained by the document object. But
JavaScript has at least one other write( ) method, so we have to specify
the document object, normally, when we use the write( ) method,
like this:
document.write()
- Because of the with (document) clause that preceeds the code block (in the curly braces), the browser knows that write( ) refers to the write( ) method that is contained by the document object. This sounds like an obvious and simplistic thing to say, but it is a very important concept.
Nested with Statements
It is possible to nest with statements. What this really means is that you can put a with statement inside another with statement.
Here is an example of how you can nest a with statement:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Nested With Statement</title>
</head>
<body>
<div id="mainDiv">
<script type="text/javascript">
/* <![CDATA[ */
with (document)
{
with (window)
{
var winLeft = screenLeft ? screenLeft : screenX;
var winTop = screenTop ? screenTop : screenY;
write("location is " + location + "<br/>");
write("screenLeft/screenX is " + winLeft + "<br/>");
write("screenTop/screenY is " + winTop + "<br/>");
}
}
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The write method is contained by the document object, as we have noted many times already.
- The properties location, screenLeft, and screenTop
are contained by the window object.
The exception to these properties is Firefox. In Firefox, you need to use these property names:- screenX instead of screenLeft
- screenY instead of screenTop
There is a really good reference page at W3Schools.com which describes this situation with Firefox.
In fact, the sample page above uses some of the code from the reference page cited above, to decide if the screenTop and screenLeft properties are available. The two relevant lines in this decision are the lines which create and assign the variables winLeft and winTop.
-
The first statement inside the inner code block (inside the second set of curly braces)
would, without
the with statements, normally be like this:
document.write("location is " + window.location + "<br/>");
break and continue Statements
Recall that the break statement is used to stop the processing of a switch statement. The break statement may also be used to stop the processing of a while, do...while, for, and for...in statement. The break statement stops the execution of the switch or looping statement and tells JavaScript to run the next statement that follows the statement being halted.
The continue statement is used only with looping statements. It tells JavaScript to interrupt the processing of the loop, but then to go back to the top of the loop and start the next iteration.
Following are two versions of similar code. The first version uses a break statement inside a for loop, which stops the for loop completely. The second version uses a continue statement in a similar for loop, which interrupts the running of the current iteration but also starts another iteration of the loop and continues its processing:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Break vs. Continue Statement</title>
</head>
<body>
<div id="mainDiv">
<h3>Results of <i>break</i>:</h3>
<script type="text/javascript">
/* <![CDATA[ */
for (var count = 1; count <= 5; count++)
{
if (count == 3)
{
break;
}
document.write(count + "<br/>");
}
/* ]]> */
</script>
<h3>Results of <i>continue</i>:</h3>
<script type="text/javascript">
/* <![CDATA[ */
for (var count = 1; count <= 5; count++)
{
if (count == 3)
{
continue;
}
document.write(count + "<br/>");
}
/* ]]> */
</script>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The first for loop stops running completely when count equals 3, because the break statement tells it to stop.
- The second for loop keeps running when count equals 3, because the continue statement causes the code to skip the rest of the current loop's statements but also to go back to the top of the loop and start another iteration. The new iteration uses count equal to 4.