JS for beginners: for Loop in JavaScript

JavaScript is one of the most popular programming languages today, if you are a newbie or you’ve just come to this field. JavaScript is a great way to start. Like every other programming languages, the very first fundamental concept you need to familiar with in this language is the for loop. So how does for loop in JavaScript work? Let’s see some definitions and code examples below.

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement to be executed in the loop.

var str = "";
for(i = 0; i < 5; i++){
str = str + i;
}
console.log(str);
Output: 01234

On this code example above, it is an example of for loop in JavaScript. Let’s take a look specifically on its syntax:

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

To define a loop in JavaScript, you have to start with for keyword, inside opening brackets and closing brackets are:

initialization:
Typically start with a counter variable. This expression may optionally start with var or let keyword like the example above, is the var keyword. Basically, Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. But variables declared with let keyword are local. (if you want to know more specifically the difference between them, read this article).

condition:
We can see i < 5 on the example above, and it initialized at i = 0. So whenever this expression is true, the statement will be executed and always remember that an expression evaluated before each loop iteration.

final-expression:
An expression is evaluated at the end of each loop iteration. It will have occurred like the way of condition. Generally used to update or increment the counter variable.

statement:
Using block element, statement starts and end with a bracket {…}. As long as these conditions evaluate to true it will be executed. Inside this, you can add multiple statements. But if you don’t want to give any statement, you can just use it (; )

And remember, everything in for loop is optional which means that initialization, condition, final-expression, and statement are not really required. Look at some of these examples below.

Using for

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

for (var i = 0; i < 9; i++) {
   console.log(i);
   // more statements
}

Optional for expressions

All three expressions in the head of the for loop are optional.

For example, in the initialization block it is not required to initialize variables:

var i = 0;
for (; i < 9; i++) {
    console.log(i);
    // more statements
}

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

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

You can also omit all three blocks. Again, make sure to use a break statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

var i = 0;

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

Using for without a statement

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

function showOffsetPos(sId) {

  var nLeft = 0, nTop = 0;

  for (

    var oItNode = document.getElementById(sId); /* initialization */

    oItNode; /* condition */

    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */

  ); /* semicolon */ 

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

}

/* Example call: */

showOffsetPos('content');

// Output:
// "Offset position of "content" element:
// left: 0px;
// top: 153px;"


Facebook Comments

Previous Article
Next Article

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
minneapolis web designIan Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Ian
Guest
Ian

Now I’m learning JavaScript and for Loop, I think it’s essential, thanks for your post, quite comprehensive. But I suggest your examples should be little shorter. Thanks, have a good day.

minneapolis web design
Guest

This is a very intriguing blog you have shared with us!

Subscribe to Our Newsletter

Categories

Archives