DEV Community

Cover image for What you may not know about loops in JS - part 1 - for loop
Mariam Reba Alexander
Mariam Reba Alexander

Posted on • Updated on

What you may not know about loops in JS - part 1 - for loop

You may have used for loop, for/of and for/in a million times on your code and you probably know by now that it is used for iterating an array or object keys (or values) and execute some code within the looping statements.

Javascript has five looping statements: while, do/while, for, for/of (and its for/await variant), and for/in. What I am going to focus upon is for, for/of and for/in loops.

for

You may very well know the syntax of a for loop

for(initialize ; test ; increment)
    statement
Enter fullscreen mode Exit fullscreen mode

and the most common example of a for loop is

for(let count = 0; count < 10; count++) {
    console.log(count);
}
Enter fullscreen mode Exit fullscreen mode

(In the above syntax, javascript evaluates initialize only once before the loop begins, test expression is evaluated before each iteration and only if it evaluates to a truthy value then the statement in the body of loop is executed. Finally the increment expression which can be an assignment expression or ++ or -- operators is evaluated.)

Loops are not that simple always, it can get complex like the below example, where you can initialize and increment multiple expressions by using comma separators.

let i, j, sum = 0;
for(i = 0, j = 10 ; i < 10 ; i++, j--) {
    sum += i * j;
}
Enter fullscreen mode Exit fullscreen mode

Now to the interesting fact of loops, in all of the above examples the variables were numeric, like i = 0 and j = 0, it does not have to be so. For example,

// Return the tail of linked list x
function tail(x) { 
// Traverse while x.next is truthy                         
 for(; x.next; x = x.next) /* empty */ ; 
 return x;
}
Enter fullscreen mode Exit fullscreen mode

The above for loop is used to traverse a linked list data structure and return the last object in the list and the first object does not have a next property.

Notice that the above code has no initialize expression.

In a for loop any of the three expressions may be omitted, but the two semicolons are required.

Now what happens if you omit the test expression ? The loop repeats infinitely.

for(;;){
console.log("Eternity"); //logs infinitely 
}
Enter fullscreen mode Exit fullscreen mode

Now you know how you can create an infinite loop other than using while(true)
infinite loop dog giffy

In the next part I will be sharing interesting facts on for/of and for/in loops.


Mariam Reba Alexander,
Frontend developer at Maersk.

Top comments (0)