background
|
|
Linux
Linux Support
A small area on the internet for Linux Support.
More icon

News
All in one Place
All of your regular news in one place.
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 3 — Looping Password

That's the woyd!

Let's go through this example line by line. View Source if you want to see the whole script.

After the typical JavaScript preamble, we start with a couple of variable declarations:

var password="pass the wrench";
var answer;

Here we define the password as a string, and we declare a variable called answer. You'll see why we had to declare answer in a second. The next few lines are the important ones:

while (answer != password) 
{
	answer = prompt("What's the woyd?","");
}

This is a while loop. while loops come in this general form:

while (some test is true)
{
	do the stuff inside the curly braces
}

So the above lines say, "While the answer isn't equal to the password, execute the prompt command." The loop will keep executing the statements inside the curly brackets until the test is false. In this case, the test will only be false when the words the user enters are the same as the password (that is, "pass the wrench").

We had to declare answer because performing a test like (answer != password) on an undeclared variable will give an error in some browsers. Because answer is given a value by the prompt method inside the while loop, it will have no value the first time we hit the loop. Defining it early gives it an initial value of "".

Although looping indefinitely is often useful, loops are more commonly used to execute a set of statements a specific number of times. Here's another example of a while loop that shows how to do this.

next page»