Greeting JavaScript: for Loop, ES6 Loops & Beyond5 min read

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.

for Loop

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;"

for in Loop

The for...in statement iterates over all non-Symbolenumerable properties of an object.

let obj = {a: 1, b: 2, c: 3};
for (let v in obj) {
    console.log(v);
}
// Expected output: a 
                    b
                    c

NOTE: The for…in loop should NOT be used to iterate over arrays because, depending on the JavaScript engine, it could iterate in an arbitrary order. Also, the iterating variable is a string, not a number, so if you try to do any math with the variable, you’ll be performing string concatenation instead of addition.

for of Loop

The for...of statement creates a loop iterating over iterable objects, including: built-in StringArrayArray-like objects (e.g., arguments or NodeList), TypedArrayMapSet, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

let list = ["a", "b", "c"];
for(let i of list){
    console.log(i);
}
// expected output: a
                    b
                    c

During each iteration, the i variable is assigned the corresponding element in the list.

The for…of loop works for other iterable objects as well, including strings:

let string = "Hello ES6";
for(let char of string){
    console.log(char)
} 
// Expected output: H
                    e
                    l
                    l
                    o
   
                    E
                    S
                    6

The for…of loop also works on the newly introduced collections (Map, Set, WeakMap, and WeakSet). We will learn about them in the upcoming articles.
Note that ES6 code will run only in browsers that support it. Older devices and browsers that do not support ES6 will return a syntax error.

Previous Article
Next Article
Every support is much appreciated ❤️

Buy Me a Coffee