Wednesday, October 15, 2014

JavaScript Tutorial – Lesson 4 pt 1

JavaScript Tutorial – Lesson 4 pt 1

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

  1. Introduction to Loops
  2. Looping Password
  3. More about While Loops
  4. For Loops
  5. Nested Loops
  6. Loop Exercise
  7. Arrays
  8. Arrays and Loops
  9. Arrays in the Document Object Model
  10. Functions
  11. Functions with No Parameters
  12. Parameters and Return Values
  13. Functions with More Than 1 Parameter
  14. 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:
01var the_password = "pass the wrench";
02
03var answer = prompt("What's the woyd?","");
04
05if (answer != the_password) {
06
07   answer = prompt("What's the woyd?","");
08
09   if (answer != the_password) {
10
11       document.write("You lose!<p>");
12
13   else {
14
15       document.write("That's right!<p>");
16
17   }
18
19else {
20
21   document.write("That's right!<p>");
22
23}
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:
1var password="pass the wrench";
2
3 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:
1while (answer != password)
2
3 {
4
5    answer = prompt("What's the woyd?","");
6
7 }
This is a while loop. while loops come in this general form:
1while (some test is true)
2
3 {
4
5    do the stuff inside the curly braces
6
7 }
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:
1var width = prompt("How many x's would you like?
2
3(1-10 is good)","5");
Next, we declare a few variables:
1var a_line="";
2
3var loop = 0;
And now for the important part:
1while (loop < width)
2
3{
4
5  a_line = a_line + "x";
6
7  loop=loop+1;
8
9}
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:
1alert(a_line);
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:
1while (loop < width)
2
3{
4
5  a_line += "x"//this was a_line = a_line + "x";
6
7  loop++;        //this was loop=loop+1;
8
9}
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. whileloops 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 …
01var a_line="";
02
03 var loop = 0;
04
05 while (loop < width)
06
07 {
08
09    a_line = a_line + "x";
10
11    loop=loop+1;
12
13 }
… could have been written using a for loop, like this:
1var a_line="";
2
3 for (var loop=0; loop < width; loop++)
4
5 {
6
7    a_line = a_line + "x";
8
9 }
for loops come in this form:
1for (initial value; test; increment)
2
3 {
4
5    do this stuff;
6
7 }
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 loopsTurn off your pop-up blocker to see this example in action.

Nested Loops

Here’s the script:
01var height = prompt("How high do you want the grid?
02
03(1-10 is good)","10");
04
05
06
07var width= prompt("How wide do you want the grid?
08
09(1-10 is good)","10");
10
11
12
13var a_line;
14
15
16
17var new_window =
18
19window.open("/webmonkey/98/04/files1a/grid.html","looper",
20
21"width=400,height=400");
22
23new_window.document.writeln("<h1>A Grid</h1>");
24
25for (var height_loop = 0; height_loop < height; height_loop++)
26
27{
28
29   a_line = "";
30
31   for (var width_loop = 0; width_loop < width; width_loop++)
32
33   {
34
35       a_line+="x";
36
37   }
38
39   new_window.document.writeln(a_line + "<br>");
40
41}
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