Menu Close

From Java to JavaScript – Loops

Loops are an essential part of programming languages. They are defined by doing a set of instructions in a repetitive manner. Endless loops also have its right to be, so they run until the parent process interrupts them. Each repetition can be further limited by defining conditions at the beginning or end of the loop. If necessary, a loop may also be end in its middle. The simplest example of a normal loop is a counter. Sometimes it makes sense to run iteratively trough a list. An example for an endless loop could be a program’s wait for new requests.

Loops in Java

Java has three different types of loops: for, while and do-while. The most less used in my experience is the do-while loop, probably because you define the condition to break the loop in the end of it, which could make the programming experience difficult.

for (int i = 5; i > 0; i--) {
  System.out.println(i);
}
 
System.out.println("do-while");
int j = 5;
 
do {
  System.out.println(j);
  j--;
} while (j > 0);
 
System.out.println("while");
int k = 5;
 
while (k > 0) {
  k--;
  System.out.println(k);
}

This example shows the different types of Java loops. The difference between the while and do-while is demonstrated. In a do-while loop the instructions are executed at least once, because the condition is checked at the end.

import java.util.*;
 
List<String> stringList = new ArrayList<String>();
 
stringList.add("0");
stringList.add("1");
stringList.add("2");
stringList.add("3");
stringList.add("4");
 
for (String el : stringList) {
  System.out.println(el);
}

There exist other types of loops like the for-in, which iterates through a list, with the difference that you don’t handle a counter variable / iterator but the element of the list. The example above demonstrates that.

Loops in JavaScript

JavaScript has the same types of loops like Java. Newer language standards have elements like the for-in or for-of statements, introduced in ECMAScript 2015 (ES6).

for (let i = 5; i < 0; i--) {
  console.log(i);
}
 
console.log('do-while');
let j = 5;
 
do {
  console.log(j);
  j--;
} while (j < 0);
 
console.log('while');
let k = 5;
 
while (k < 0) {
  k--;
  console.log(k);
}

This example show the different types of JavaScript like in the Java code above. You could also use functionality like the .forEach(callback(value, index)) array prototype function.

Comparing the for/do/do-while example: Executing the Java code took roughly 25% more time on my machine than the JavaScript code, most likely because of the JVM). Note that this is only a side information and not a proof of performance.

Leave a Reply

Your email address will not be published. Required fields are marked *

12 − 10 =

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