background
|
|
Random

Hosting
My-Hosts.com
Cheap Hosting, domain registration and design. Check this out for more details.
More icon
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Thau's JavaScript Tutorial
Lesson 4

by Thau!

Page 2 — Introduction to Loops

Sometimes you want to do the same thing more than once. Let's say, for example, that you wanted to get a password from somebody and you wanted to keep asking until they gave you the right password. If you just wanted to give them two tries, you could do something like this:

var the_password = "pass the wrench";
var answer = prompt("What's the woyd?","");
if (answer != the_password) {
	answer = prompt("What's the woyd?","");
	if (answer != the_password) {
		document.write("You lose!<p>");
	} else {
		document.write("That's right!<p>");
	}
} else {
	document.write("That's right!<p>");
}
Unfortunately, this sort of thing won't work if you just want to keep asking until they get it right. And it's pretty ugly already — imagine if you wanted to ask four times instead of just two. You'd have four levels of if-then clauses, which is never a good thing.

The best way to do similar things more than once is to use a loop. In this case, you can use a loop to keep asking for passwords until the person gives up. Here's an example of a while loop in action. The password is: pass the wrench.

next page»