Call Us Today!

Blog

JavaScript Basics: Loops

JavaScript LOOPS: program the browser to do something over, and over, and over again

JavaScript, like any modern programming language, allows you to use loops to automate repetitive processes. Loops are arguably the single most powerful part of any programming language, since they allow you to repeat a process hundreds, billions, or potentially an infinite number of times, just by writing a few lines of code.

If you’ve been following along with our tutorial series, you’ve already learned how to:

  1. create a JavaScript file and link it to a web page
  2. access the JavaScript console in your browser
  3. work with JavaScript variables
  4. work with conditions, like IF statements and switches

Either way, whether or not you’ve been following along with the series, you’ll want to download this week’s code files, by clicking HERE.

What are JavaScript Loops?

JavaScript Loops are snippets of code that tell the browser to do something over and over and over again. There are several types of loops in JavaScript. Two of the most commonly used are called “while” and “for” loops.

“While” Loops

var i=0;
while (i < 10) {
console.log("The number is " + i);
i++;
}

Before reading on, try running this piece of code in the console of your browser, and see what it does!

If you’ve just run it in the console, you’ve seen that this code prints out the following lines:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

Writing this tiny bit of code is certainly easier than typing that all out for yourself. This time-saving awesomeness of computer programming becomes much more apparent if you change the (i < 10) to an (i < 1000). What do you think will happen if you change that in the console and hit “enter”? Try it now.

It writes out that line a thousand times — and if you have a computer that was made within the past couple of decades, it probably did it almost instantaneously. You could do the same thing with much higher numbers, like a million or a billion, but it may put some more strain on your computer’s ability to keep up. You could even create an “infinite loop” and have the browser print out every number from 0 through infinity… but your browser would crash almost instantaneously. We wouldn’t recommend it, but if you want to crash your browser, you could try using while (true) instead of while (i < 10).

As you may have guessed by now, the while loop runs the code inside the { … } curly braces, over and over again, while the condition inside of the ( … ) parentheses is true. So if you use while (true) { … }, the code inside of the curly braces will run an infinite number of times. If you use while (i < 10), then the code inside the curly braces will run as long as the value of the variable “i” is less than 10.

Breaking Down the While Loop: Line By Line

var i=0; — Here we are declaring a variable called “i” and initializing it to (giving it an initial value of) zero. We are calling this variable “i” as a shorthand for “iterator,” which is pretty common in JavaScript programming. We could just as easily call this variable anything else — we could call it fvi, we could call it codingIsSuperFun, or we could call it simply “x” — but “i” is commonly used when it comes to creating an “iterator” variable for a loop.

What is an iterator, you ask? Well, something that iterates, of course! Iteration means “the repetition of a process.” So this variable helps us repeat the process that is happening inside of the { … } curly braces.

while (i < 10) — This is the condition upon which the while loop executes. While “i” is less than 10, the code inside the curly braces will execute.

There are only two lines of code inside of the curly braces in this case:

console.log("The number is " + i);
i++;

The first line writes in the console “The number is ” and then inserts the value of i. The second line, i++, is a very common shorthand way of writing…

i = i + 1;

…which means that every time the while loop executes, the value of i grows by one. Since we gave “i” an initial value of zero (var i=0;), the first time that the while loop executes, the console logs “The number is 0,” and then changes the value of i from zero to one. The second time the while loop executes, the console logs “The number is 1,” and then changes the value of i from one to two. You get the idea.

“For” Loops

While loops and for loops do basically the same thing, but in slightly different ways.

Here’s an example of a for loop that does exactly the same thing as the while loop we examined above:

for (var i=0; i < 10; i++) {
console.log("The number is " + i);
}

Try running this code in the console and see what happens. It should be the same as above.

You’ll notice that this code has all the same elements as the while loop above; just in a different structure. The same way that you could communicate the same thing by writing two different sentences. “There’s a dog over there” means the same thing as “a dog is over there,” or, if you’re Yoda, “over there, a dog there is.”

For loops tend to be a little more concise than while loops in cases like this, where we are repeating a process through a set number of iterations. While loops tend to come in handy in other cases; for example, executing a function while the user is logged in to your site’s membership area, or while the user is holding down a specific button.

Creating Your Own Loops Using Recursive Functions

You could also create your own loop, by creating a “recursive” function. A recursive function is a function that calls itself. For example:

var i=0;
(function fviStudentTestLoop() {
console.log("The number is " + i);
i++;
if (i<100) { fviStudentTestLoop(); }
})();

Run this code in the browser and see what happens.

In this case, we created a function called fviStudentTestLoop, with an IF statement inside. If i<100, we “invoke” or “call” the function again — or more precisely, the function calls itself again. This syntax — fviStudentTestLoop(); — is how we call a function. It basically tells the browser “run the function called fviStudentTestLoop.”

By putting the function in ( … ) parentheses and ending it with a closed pair of parentheses, we allow the function to invoke itself one time. However, the reason that the function is able to repeat itself over and over 100 times is because it is calling itself with the line fviStudentTestLoop();

Now it’s time for the fun part: using loops in a real JavaScript program.

Using JavaScript Loops

Look at the JavaScript file, codingIsFun.js, in the folder that you downloaded. See how many loops you can find in there!

There’s a “for” loop on line 5 that generates 100 asteroids in the HTML document, and there’s a recursive function from lines 84 through 139, that calls itself every 10 milliseconds (see line 138).

Try double-clicking on the “playWithCode.html” file to open it in the browser and see the asteroid storm in its full glory! Try playing around with the code and see what happens. Try making 200 asteroids show up. Try speeding up the asteroids. You may need to do some (or a lot) of googling in order to understand what some things mean in the code. That’s fine! Even veteran coders use Google, all the time.

Have fun! And don’t forget to join us in the coming weeks, as we create the impact/damage and score-keeping features of our video game.