For Loops in JavaScript

Just like an IF statement, a FOR loop in JavaScript is another kind of control structure.
For a review on what a control structure is, please see our last post on IF statements.

The for loop’s main purpose is to force the JavaScript engine to re-run lines of code a specific number of times. This is in contrast to the IF statement, which is used to potentially SKIP certain lines of code.

The processes of re-running lines of code over a specific number of intervals is known as iterating.

So the programming “jargon” for the for loop is to say “I’m iterating through my FOR loop”, which just means that you’re re-running the same lines of code over and over again.

What’s the Purpose of a FOR Loop?

Re-running the same lines of code over and over again may seem a bit strange to someone who is new to programming, but let me assure you, it’s incredibly useful and opens up HUGE possibilities for the creation of useful programs.

Let’s take a look at the syntax for the FOR loop in JavaScript… if you come from a Java programming background it will look very similar (with the exception of the introduction of the dynamic typing concept):

for (var i = 0; i<10; i++)
{
// insert code to be iterated here
}

For those of you who haven't seen these for loops before, this likely looks like a bunch of random letters and symbols. But let me assure you, they all have their purposes.

Note: Java programmers, take notice that we didn't declare the variable i as an int, we just used the var keyword due to the dynamic typing.

Alright, let's take a look at a generic version of JavaScript's for loop:

Used to mark the starting point of the iteration of the for loop. In most cases, you would use a variable called i and initialize it with the value of 0.

Termination

Used to decide when the JavaScript engine should STOP iterating over the code in the loop and exit out of the scope of the loop.

Iteration

Used to determine HOW the loop will iterate each time it starts the loop over again. Most times you will use the code i++ which is used to increment the value of the variable i (initialized in the Initialization statement) by 1.

When to Use a FOR Loop in JavaScript

Alright, so you're familiar with what a FOR loop looks like, but you might be asking yourself when you'd want to use one.

Let me answer that question with an example.

Here's some code that I use to do something stupidly simple: output the numbers 1 through 15 to the console:

I know, I know, this is a silly program, but I'm using it to illustrate a point.

This is an example of what a loop (specifically a FOR loop) is needed.

How do I know? Because there is some series repetition going on here.

Whenever you see repetition in code like this, it's probably a good idea to consider using a loop.

So how could we use a for loop to create the same output as the program above? Let's find out:

for (var i=1; i<=15; i++)
{
console.log(i);
}

Done and done!

What Are the Inner Workings of the FOR Loop?

Here's what's going on in the FOR loop:

First it will run the initialization statement (it only runs this code once), that's the code that declares the variable i and sets it equal to 1.

Now that the for loop has declared the variable that it will be using to "execute" the loop, it moves on to check and see if it should terminate the looping... I know, it's a bit silly that it should have to check IMMEDIATELY if it should stop looping before its had a chance to do even ONE iteration, but believe it or not, this is a good thing, as it's predictable.

So, since it checks to see if it should terminate, it will run the termination condition, which at this point would be "Is i less than or equal to 15", and since i was just initialized as 1, it's checking if 1 is less than or equal to 15. Last time I checked, this was true, so it will execute the code inside the scope of the FOR loop.

The code inside the scope of the FOR loop is console.log(i), and remember that the current value of i is 1, so it will output "1" to the console. Great!

Then, since there's only one line of code in the scope of the FOR loop, it will try to loop over the entire scope of the FOR loop again. But before it loops, it need to go through a process that it ALWAYS goes through, which is to run the code in the iteration statement, then run the code in the termination condition statement.

Keep in mind that it ALWAYS runs the code in the iteration statement, then it runs the code in the termination condition statement. Over and over and over and over until the termination condition evaluates to false.

So for our example, what happens?

Well it runs the iteration statement, which is just i++, which increments the value of i by 1. So i now equals 2!

Then it runs the termination condition statement... "Is 2 less than or equal to 15?", yes it is! So... iterate again!

It will then output the number 2 to the console. Then it hits the end of the scope, so it will need to iterate, and possibly terminate. And round and round it goes until eventually, i is incremented to 16. Then when it runs the termination condition and asks "Is 16 less than or equal to 15?" the answer is false, so it terminates the loop.

And the result is that it has now outputted the numbers 1 through 15 to the console... which is exactly the same result as our code where we didn't use the for loop... but with our for loop program, we wrote a LOT less code!

Imagine if our requirement was to output the numbers 1 through to 1 million onto the screen... that would be a TON of typing if we weren't using a for loop. But WITH a for loop, it's the same amount of code as when we wanted to show numbers 1 through 15.

Neat right?

Thank god for FOR loops 🙂

In Summary

Programming languages need loops. Without them, we just wouldn't be able to create the programs that we have available today.

Loops are not only a time saver, but have also saved the fingers and wrists of hundreds of thousands of programmers, possibly thwarting a global epidemic of carpal tunnel syndrome. So be sure to send a thank you letter to the creator of loops! And hey, if you happen to know who it was that created loops in programming, let me know in the comments section below.

And as always, don't forget to enter your email address in the box below this post. I'm giving away a free goodie for everyone who signs up, and it's sure to turn you into an even smarter cookie than you already are... and hey, no need to send me any thank you letters, it's my pleasure!