Welcome to Lesson 4! There are two main parts to JavaScript: the syntax of the language and its library of objects. In Lesson 2, which was an introduction to the syntax, we looked into variables, statements, and if-then clauses, which are parts of all programming languages. Now it’s time to learn the rest of the JavaScript syntax.
There are only three major aspects of JavaScript syntax that we have yet to cover: loops, arrays, and functions.
Let’s start with loops.
Contents
- Introduction to Loops
- Looping Password
- More about While Loops
- For Loops
- Nested Loops
- Loop Exercise
- Arrays
- Arrays and Loops
- Arrays in the Document Object Model
- Functions
- Functions with No Parameters
- Parameters and Return Values
- Functions with More Than 1 Parameter
- Lesson 4 Review
|
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:
01 | var the_password = "pass the wrench" ; |
03 | var answer = prompt( "What's the woyd?" , "" ); |
05 | if (answer != the_password) { |
07 | answer = prompt( "What's the woyd?" , "" ); |
09 | if (answer != the_password) { |
11 | document.write( "You lose!<p>" ); |
15 | document.write( "That's right!<p>" ); |
21 | 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.
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:
1 | var password= "pass the wrench" ; |
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:
1 | while (answer != password) |
5 | answer = prompt( "What's the woyd?" , "" ); |
This is a while loop. while loops come in this general form:
1 | while (some test is true ) |
5 | 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.
More about While Loops
You should have seen as many x’s as you asked for. Let’s go over this:
First, we ask for the number of x’s:
1 | var width = prompt("How many x's would you like? |
Next, we declare a few variables:
And now for the important part:
This says, “while the variable loop is less than the requested width of the row of x’s, add another x to the line and then add one to the value of loop.” This loop will keep adding an x to the line and adding one to the value of loop until loop is no longer less than the requested width. Here’s a timeline of what happens when a person chooses two x’s at the prompt:
- Time 1
- a_line = “” (because we initialized it to be “”)
- loop=0 (because we initialized it to be 0)
- width=2 (because that’s what the user asked for)
- 0 is less than 2 so
- a_line = a_line + “x”, so now a_line = “x”
- loop=loop+1, so now loop = 1
- Back into the loop: Time 2
- loop=1
- width=2
- a_line = “x”
- 1 is less than 2 so
- a_line = a_line + “x”, so now a_line = “xx”
- loop=loop+1, so now loop = 2
- Back into the loop: Time 3
- loop=2
- width=2
- a_line = “xx”
- 2 is NOT less than 2 so
- fall out of the loop and do what follows
And what follows is:
Throw up an alert box announcing a_line.
This sort of loop is so common that programmers have developed a few shortcuts. Using the shortcuts, the while loop could have been written like this:
The first line, a_line += "x"
, says “add x to myself.” This shortcut works with numbers, too. If you have a_number = 5
, and you write, a_number+=3
, it’s just like writing a_number=a_number+3
. Programmers are lazy; they’re always coming up with shortcuts like this.
The next line, loop++
, means “add one to myself.” So, loop++
is the same as loop=loop+1
, which could also be written loop+=1
. Each of these is equally good. Which one you use depends on how lazy you are.
Just like there’s more than one way to add 1 to a number, there’s more than one way to write a loop. while
loops aren’t the only kind of loops out there. Another popular one is the for
loop.
For Loops
The while loop from the last example, which was written like this …
09 | a_line = a_line + "x" ; |
… could have been written using a for
loop, like this:
3 | for ( var loop=0; loop < width; loop++) |
for
loops come in this form:
1 | for (initial value; test; increment) |
So, the above for
loop sets loop = 0
and says that you should keep adding 1 to loop
as long as loop < width
. It’s just like the previous while
loop with a few less lines. Both say “add an x to a_line</font> <code>width
times.”
One more thing about loops before we do an exercise using them: Loops can be nested. Here’s an example of
nested loops.
Turn off your pop-up blocker to see this example in action.
Nested Loops
Here’s the script:
01 | var height = prompt("How high do you want the grid? |
07 | var width= prompt("How wide do you want the grid? |
19 | window.open( "/webmonkey/98/04/files1a/grid.html" , "looper" , |
21 | "width=400,height=400" ); |
23 | new_window.document.writeln( "<h1>A Grid</h1>" ); |
25 | for ( var height_loop = 0; height_loop < height; height_loop++) |
31 | for ( var width_loop = 0; width_loop < width; width_loop++) |
39 | new_window.document.writeln(a_line + "<br>" ); |
After asking for height and width, opening a new window, and writing a header to it, we go into a for
loop. The first for
loop sets a_line = ""
. Try doing the example without this line and see what happens. After initializing a_line
, the script goes into another for
loop to build a line of x’s as wide as required and prints it out to the new window. This happens height
times.
OK, here’s your assignment: Take a look at this
loop exercise and try doing it on your own before viewing source to see how it works.
Turn off your pop-up blocker to see this example in action.
Loop Exercise
This script asks for a few words and then prints them out in reverse order. Try writing the script yourself. When you’re done, View Source on this to see how I did it. After you’ve figured it all out, it’s time to learn about.
No comments:
Post a Comment