Design Development JavaScript

JavaScript 101-#14 – Loops Pt1

Table of Contents

In this part of JavaScript 101 we will take a look at one thing that will help you do your work faster, better and with less code. This subject is one of the favorite for many of programmers in any programming language. Our topic for today, and probably one future post, are loops! In this part we will discuss what they are, how they work and also explore more-in-depth at least one of them. Let’s dive in …

What

Loops exist in every programming language. Their purpose is to help us automate same tasks that needs to be done more than once. For example, let’s say you have a paragraph of text and you want to print every character into console. You can either spent half of day (depending on length of text) by writing dozens of console.log() commands manually or you can create loop that will go through whole text, from first to last letter, and print it out for you. You don’t have to be or think like a programmer to prefer the second choice.

This is only one example for using loops and we will write our own later on, however, more complex one can be loop nested inside if statement. We talked about if statements in previous part of JavaScript 101 series. Imagine asking user for some input data via prompt() or confirm() method. Based on the data, you will then use if statements with loops for specific conditions.

How

In JavaScript, and also another programming languages, we can use two types of loops – “for” loop and “while” loop. Let’s take a look at “for” loop as first.

For loop

“For” loop consist of two parts – three parameters and block of code to be executed. Parameters are inside parenthesis and divided by semicolon. These parts are initialization, condition, increment. Code block is placed inside curly brackets. When you create a loop, it will start on initialization point and continue according to specified increment until the condition is returned as false. Code inside brackets is executed every time. The syntax starts with “for” keyword, followed by parenthesis with parameters and curly brackets.

JavaScript:

for (initialization; condition; increment) {
 …
}

Since the best way to understand and learn something is to try it by yourself, we will code our first example. In lines above, we talked about printing characters from paragraph to console. So, let’s start with this. First, we will create new variable “text” with string of some text. I chose great programming quote by John Woods.

JavaScript:

var text = “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”;

Next step is to create the “for” loop. As said, this loop takes three parameters. First one is where it will start. We will define this by creating another variable “i” with value of 0 – var I = 0. Second parameter, condition, will be that i has to be lower than the last index of character from text – i < text.length. Third parameter is for increment. Since we want to print every character, we will increment by one – i++ (shortcut for 1+1 (Do you understand the name of C++ now?)).

JavaScript:

var text = “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”;
// “i” is often used by programmers because it sounds like shortcut for “integer”, “j” is just next in alphabet
for (var i = 0; i < text.length; i++) {}

Inside the curly bracket we will use console.log() method to print out every character. To do that we have to access every character by index by writing “text[i]” as a parameter for that method. “text” is name of variable and “i” is for number generated by loop.

JavaScript:

var text = “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”;
for (var i = 0; i < text.length; i++) {
 console.log(text[i]);
}

The result will be text split into individual characters. Everyone on its own line. Before we move to another example, there is a way to optimize our loop and make it run faster. All we have to do is to modify the first and second parameter. We will create another variable (as an argument for loop) called “j” and set it to “text.length”. Variables will be divided by comma, like when you create multiple variables at once in the regular way. The second argument will be changed to “i” is lower than “j” – i < j.

JavaScript:

var text = “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”;
for (var i = 0, j = text.length; i < j; i++) {
 console.log(text[i]); // result - A, l, w, a, y, s …
}

The reason why this way is faster is in “text.length” part. To explain it … The second argument – condition – is checked every time the loop is running. Quote used for this example has about 113 characters. This means that loop is counting all characters in “text” variable 113 times – in other words, in every iteration. By creating new variable (“j”) and moving it inside the first argument, loop will count amount of characters only once and it will save the number into this variable. In every new iteration, when it will need to compare current number of iterations (“i”) to total amount of characters (“j”), it will just access the variable “j” with specific number instead of going through whole text and counting it again.

For next example will create loop printing out every second number from zero to one hundred. First parameter will be variable “i” set to zero and another variable “j” set to one hundred (to optimize loop). Second argument, condition, will be “i” is lower than “j”. Third argument will be “i += 2” (shortcut for i = i + 2). To print the numbers we will again use console.log() method with “i” as parameter.

JavaScript:

for (var i = 0, j = 100; i < j; i += 2) {
 console.log(i); // result – 0, 2, 4, 6, 8 …
}

Since we are talking about the loops, there is something very important we should discuss. It is called infinite loop. As you probably guessed, this kind of loop will run forever or until it will crash your browser or computer. In case of “for” loop you can create infinite loop very easily by modifying the second parameter. All you have to do is, for example, to set “i” to one, “j” to zero and condition to “i > j”. After that, it will run forever because it will never return false – anything more than one is bigger than zero.

JavaScript:

// infinite loop – will you try it?
for (var i = 1, var j = 0; i > j; i++) {
 …
}

Summary

That’s all for this part of Loops. In the next one we will try couple more examples of “for” loop and take a look at next type of loop called “while” loop. Until that time, practice on your own examples to fully understand how “for” loop works. If you want to explain anything we talked above, write me a message or leave a comment.

If you liked this article, then please consider subscribing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.