JavaScript

JavaScript For Loop Example

We hear a lot about loops, especially ” for loop “. So what, in fact, are they? They’re just pieces of code that repeat the same commands several times, until you reach a desired conclusion, without getting you bored out of your mind, repeating your code. This is how we JavaScript guys do it.

Syntax

You will definitely have to know the syntax of for loops and that goes like this:

for ([initialization]; [condition]; [final-expression]) statement

You’ll see in the examples how each of these clauses is translated into code. So let’s start right away.

Using simple for loops

The most typical way to use for loops is counting. You just need to tell the loop where to start, where to finish, and with what pace to count. This is how the code goes for counting and printing in the screen odd numbers from one to ten:

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

According to the syntax structure we gave you above, you can now easily distinguish that we have first declared and initialized the variable with the value 1. We have set the condition, which in our case is to not count odd numbers greater than 10, and the final one is the pace, and since the two closest odd numbers only differ by 2 the final expression is i+2. Notice that we start the loop with an odd number.

Removing for loop’s clauses

One way to put for loops in good use would be to optimize them, by removing the expressions.Each one of them can be omitted, or you can even omit them all. We will be using the same code of the example above, only we’ll modify it according to the thing we want to show you, so that you can draw the differences and understand it more. Firstly, we’ll show you when and how can you remove the initialization expression. Have a look at the code to see how it changes:

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

You will definitely notice that we have removed the initialization expression, but the variable is initialized outside the loop before we write the code for the loop. Also what’s important here is that the place where the expression we removed was is still there, even though it’s now empty. It’s not correct to remove the semicolon saving that space.

Now it’s time to show you how to use a for loop with all three blocks removed. This is the code:

i=0;
for (;;) {
    if (i > 3) break;
    console.log(i);
    i++;
}

You are obliged to declare an initialize the variable before writing the rest of the loop’s code. If you don’t want to put a condition or a way to get out of the loop, you would be building an infinite loop. But if this is not your intention then you will have to put a condition and an expression that changes the value of the variable, as we have done in the previous code snippet.

for loops and break;

If you were careful in watching the code snippets above you will see something that we did not explain: the expression break;. That expression is used to jump out of the loop, which means that it takes the command right after the loop, without executing the rest of it, but instead doing whatever code is next. Here’s an example of how you can use it:

var text = ""
var i;
for (i = 0; i < 10; i++) {
	if (i == 3) {break;}
	text += "The number is " + i + "<br>";
}

This code snippet prints out the value of the i variable, and increments it by one. When the value of i reaches 3, it breaks out of the loop. That is how the break; expression operates.

for loops and continue;

The continue; expression is similar to break; only this one only breaks out of the current iteration, and into the next one, not necessarily out of the loop. Here’s the modified example:

var text = ""
var i;
for (i = 0; i < 10; i++) {
    if (i == 3) {continue;}
    text += "The number is " + i + "<br>";
}

Instead of break; we have used continue; and the difference is that the next iteration to be executed is not the one after the loop, it’s the one after the iteration containing continue;.

for…in loops

The for...in loops are a way of iterating only the properties of different objects.It’s sytax is like this:

for (var variable in objectExpression) {statement}

Any expression that evaluates to an object can be used as objectExpression, and this object’s properties are the ones to be iterated. On each iteration, the property names are assigned to variables, and then the statement is executed.See the example below:

var myObj = {a: 1, b: 2, c: 3}, 
    myKeys = [];
 
for (var property in myObj) {
    myKeys.push(property);
}
 
myKeys; 

//['a','b','c'];

Note that the properties’ values are actually strings, so whatever action you want to do with, or on them in the statement block, you will have to think of them as such.

Using for with an empty statement

The awesome part about JavaScript is that almost every modification of the code leads you somewhere useful. That is the case with the following code, which we’d like you to see first and discuss later:

function showOffsetPos (sId) {

    // initialization
    var nLeft = 0, nTop = 0;

    // condition
    for (var oItNode = document.getElementById(sId);
        // final-expression
         oItNode;
         nLeft += oItNode.offsetLeft,
         nTop += oItNode.offsetTop,

          // empty statement
         oItNode = oItNode.offsetParent) ;

    console.log("Offset position of \"" + sId + "\" element:\n left: "
        + nLeft + "px;\n top: " + nTop + "px;");
}

showOffsetPos("content");

This loop calculates the offset position of a node in the final-expression section, therefore making the use of a statement block useless, so the empty statement is used instead.

Download the source code

This was an example of for loops in JavaScript.

Download
You can download the full source code of this example here: ForLoops

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

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

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
jolla beach
10 years ago

I’ll immediately grab your rss as I can not to find your e-mail subscription link
or newsletter service. Do you have any? Kindly allow me understand
in order that I could subscribe. Thanks.

jsc42
jsc42
8 years ago

In the ‘Using simple for loops’ and ‘Removing for loop’s clauses’ sections, the final part of the for loops should read ‘i += 2’, not ‘i+2’.

Back to top button