Introduction to Programming

Page 4

Getting Loopy

Looping is often used for actions like counting through a list and applying a certain function to each element in that list, or testing for a condition and repeating the process until the condition is false. It essentially allows a program to repeat pieces of the code. For example, a loop could be used to repeat a sequence of actions on each number between 1 and 8, or it could continue to collect information from a user until it's indicated that the user is done.

The two main kinds of loops are conditionals (like the while loop in JavaScript) and iterated (the for and for in loops in JavaScript). You'll usually encounter iterated loops, so I'll focus on them. As I stated earlier, they are mainly used for counting purposes. For in is for more specific applications. It sifts through the properties of an object, which is useful when you don't know the number of properties. Here's the basic structure for a loop:

for (initial value; test; increment)


{


do this stuff;


}

Here's a loop as it might be used in a function:

for (i=0; i < thePasswords.length; i=i+1) {


if (enteredPassword == thePasswords[i]) passwordMatches = true;


}


return passwordMatches;

Let's break down the loop into three parts so it's easier to understand. The first part of the for loop (i=0) sets its initial value. In this case, the initial value is 0. The second part, i < thepasswords.length, is evaluated until the return value is false. The third part says what to do to i each time the loop runs. When part two is not true, the looping will stop. The function will return false if enteredPassword doesn't match any of thePasswords[i]. The if statement just says if your password matches i, then change the value of passwordMatches to true, which in turn makes the getPassword function true.

Now let's put it all together with functions.


To Next Page

 

BreBru.com Information Technology HTML